首页 > 解决方案 > Mongoose:使用 findOne() 查询嵌套数组并投影出来

问题描述

我有一个包含以下结构的文档的 Cities 集合:

city = {
    "_id" : ObjectId("5b7b9eac23cad92dbd81f92b"),
    "stores" : [
        {
            "name" : "someName",
            "storeId" : "5b9350dc97c35614731e03df"
        }
     ]
}

如何通过 storeId 查询集合 Cities,并使用 findOne() 获取 Mongoose 中的城市对象?

我尝试了以下方法,但在这两种方法中我都得到了'null'

query = {
   'stores.storeId' : someId
}

query = {
   'stores': {'$elemMatch': {'storeId': someId}}
}

Cities.findOne(query)
.then( city => {
   console.log('city: '+ city);
});

然后我试图只突出名字。我考虑过使用:

options = {
   select: { 'stores.$.name': 1 }
}

Cities.findOne(query, {}, options)
.then( name => {
   console.log('name: '+ name);
});

但我不知道它是否会起作用,因为我什至没有成功查询它......

标签: mongoose

解决方案


我发现了错误: ...在数据库中,storeId 被保存为字符串而不是 ObjectId,但在架构中它被设置为 mongoose.Schema.Types.ObjectId。当我将架构更改为字符串时,找到了该文档。


推荐阅读