mongoose - 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);
});
但我不知道它是否会起作用,因为我什至没有成功查询它......
解决方案
我发现了错误: ...在数据库中,storeId 被保存为字符串而不是 ObjectId,但在架构中它被设置为 mongoose.Schema.Types.ObjectId。当我将架构更改为字符串时,找到了该文档。
推荐阅读
- r - 将txt文件加载到R中并根据其他数据框替换一些值
- vue.js - 如何将任务添加到我的 Vue 2 待办事项应用程序的列表中?
- python - 来自文本文件的 Python 总和对
- python-3.x - 动态查找和“替换”方法时发生冲突
- javascript - ngx-extended-pdf-viewer 中的默认水平滚动不工作
- python - LSTM 时间序列输出与实际数据不匹配
- sql - TimescaleDB - 如何获得行之间的时间戳差异?
- python - django for loop on html 无法检索其 object_lists 的每个数据字段
- python - 如何在 conv2d (PyTorch) 中动态更改内核的大小?
- typescript - 打字稿:对象初始化时动态计算的字段