猫鼬findOne,如何从对象数组中查找元素?

时间:2020-01-11 08:22:22

标签: node.js mongoose

我正在尝试查找并检查该用户是否对某项商品具有价值。

样本模型数据

user: {
    _id: 1,
    profilePictures: [
        {
            id: 1,
            image: 'sample.png'
        },

        {
            id: 2,
            image: null
        },

        {
            id: 3,
            image: null
        }
    ]
}

我的Mongoose.find查询

const user = await userModel.findOne({
                                    _id: 1,

                                    profilePictures: {
                                        $elemMatch: {
                                            $and: [
                                                { id: 2, image: null },
                                                { id: 3, image: null }
                                            ]
                                        } 
                                    }
                                })

但是它什么也没返回,我知道我可以让用户使用profilePictures或其他一些Array函数上的Array.some()来检查位置2和3的数组项是否也具有值为的属性图像空

但是由于我正在学习猫鼬,所以我试图找到一种方法来做到这一点。

2 个答案:

答案 0 :(得分:0)

假设您需要查找特定索引的文档,并且数组只是一个级别,则可以使用此简单查询

values-night

答案 1 :(得分:0)

因此,到目前为止,我想出了一个不使用复杂的猫鼬查询的解决方案。 我刚刚使用JavaScript进行了验证。

// req.body.id is an array of number

const user: any = await db.getCollection('somecollection').findOne({ _id: 1 })

let isAllPositionAvailable = true

for (const position of req.body.id) {
    isAllPositionAvailable = user.profilePictures.find((x: any) => x.id === parseInt(position)).image === null

    if (!isAllPositionAvailable) break
}

if (!isAllPositionAvailable) {
     return res.status(400).send({
          message: 'Image position is not available, please remove the existing image first'
     })
}