node.js - 根据子索引从嵌套数组中获取两层深度的数据
问题描述
我有这个 json 模式
"header": {
"self": {},
"items": [
{
"_id": "5ec7e61979ec9914ecefc539",
"title": "Test",
"root": "true",
"alignment": "left",
"page": "test",
"translate": "",
"toggle": "",
"icon": "",
"IsActive": 1,
"submenu": [
{
"_id": "5ece913a353a71309084768d",
"title": "Sub Test",
"bullet": "dot",
"page": "test",
"translate": "MENU.TEST1",
"icon": "flaticon-stes-3",
"IsActive": 1
},
{
"_id": "5ece935d79972f0390997179",
"title": "Sub Test",
"bullet": "dot",
"page": "test",
"translate": "MENU.TEST2",
"icon": "flaticon-stes-3",
"IsActive": 1
}
]
}
]
}
// Index based on a previous query
this.db.collection('AssetData').find({"header.items.$.submenu.[0]._id":ObjectID("5ece913a353a71309084768d"));
//Tried with elemMatch
this.db.collection('AssetData').find(
{
"header.items": {
$elemMatch:{
"submenu": {
$elemMatch:{
"_id":ObjectID("5ece913a353a71309084768d")
}
}
}
}
});
而且我想根据子菜单中的 _id 检索子菜单对象数据之一,但我无法检索它。
我不确定我是否可以使用来自另一个查询的第二个数组的索引来获取数据,或者是否还有另一种我缺少的方式,比如 elem 匹配。
我正在使用 MongoDB 3.5.6。
检索这个的最佳方法是什么?
解决方案
// Index based on a previous query
this.db.collection('AssetData').find({"header.items.$.submenu.[0]._id":ObjectID("5ece913a353a71309084768d")});
//Tried with elemMatch
this.db.collection('AssetData').find(
{
"header.items": {
$elemMatch:{
"submenu": {
$elemMatch:{
"_id":ObjectID("5ece913a353a71309084768d")
}
}
}
}
}).exec(function(err, item) {
console.log(item);
// here you can retrieve the stock from item, as you wish
});
希望它会帮助你
推荐阅读
- c - 如何使用 C 读取主文件表 (MFT)?
- vue.js - 如何传递多个突变来更新 Vuex 存储?
- python - 如何在迁移步骤中修复 OnetoOneField 中的唯一约束
- reactjs - Material UI 的工具提示 - 自定义样式
- javascript - 在javascript中查找重复值及其重复次数
- flutter - 用颤动动画显示或隐藏小部件
- android - 错误:在项目“应用程序”中,已解决的 Google Play 服务库依赖项依赖于另一个确切版本的依赖项
- amazon-web-services - 使用请求路径从 AWS API Gateway 返回 302
- javascript - 如何将嵌套的对象数组转换为 Reactjs 中的字符串数组?
- reactjs - 显示字符串时如何显示换行符?