node.js - 如何在 Mongoose 中搜索具有两个元素的对象数组

标签 node.js

我的模型中有这个对象

{
    "name" : "one",
    "items" : [ 
        {
            "foo" : "1",
            "bar" : "2"
        }, 
        {
            "foo" : "1",
            "bar" : "3"
        }
    ]
},...

当我查询时

myModel.find({
    "items.foo": "1",
    "items.bar": "2"
}

结果是名称为一的对象,这是正确的,但是当我查询时

myModel.find({
    "items.foo": "1",
    "items.bar": "3"
}

它应该找不到任何结果,但是,出乎意料的是,它再次产生名称为一的对象。 我尝试过,但发生了相同的结果

myModel.find({
    $and :[{
    "items.foo": "1"},
    {"items.bar": "3"}
]}

有什么建议我应该做什么吗?

最佳答案

它应该有效:

myModel.find({
            items: {
                $elemMatch: {
                    $and: [{
                            foo: "1"
                        },
                        {
                            bar: "3"
                        }
                    ]
                }
            }
})

关于node.js - 如何在 Mongoose 中搜索具有两个元素的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60017940/

相关文章:

javascript - Node.js Express 没有响应

javascript - Content-Security-Policy 阻止 Vue.js

node.js - 如何找到我的 mongoDB 的远程 URL 以在我的 Node.js 代码中使用?

node.js - moment.js 格式 TZ 格式的日期

Node.js + Mongoose/Mongo 和缩短的 _id 字段

Node.js 在 url 上隐藏 html 名称

node.js - Mongoose 复杂(异步)虚拟

Node.js 远程 mp3 文件持续时间和比特率

javascript - package.json 的 main、module、browser 属性应该指向 minified 还是 source?

node.js - API 未根据 lambda 授权方的响应调用 lambda 并返回空消息