猫鼬:使用findOne()查询嵌套数组并投影出来

时间:2018-09-08 05:19:01

标签: mongoose

我有一个收集城市,其文件结构如下:

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

如何通过storeId查询集合城市,并使用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);
});

但是我不知道它是否可行,因为我什至没有成功查询它...

1 个答案:

答案 0 :(得分:0)

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