如何通过嵌套子id找到文档

时间:2016-09-10 11:03:41

标签: javascript node.js mongodb algorithm

我在我的文档中嵌套了子项,我希望找到任何children._id文档 我的文件如下所示。

例如:

我想要这个child._id“PxX4EYMYVDOphx8XU”如何找到这个文件。

[{
  "_id": "v4jdHchuogyumed7f",
  "name": "products",
  "children": [{
    "_id": "fDE1kyR081Y44aO7h",
    "name": "Clothes",
    "children": [{
      "_id": "l464EYMYVDOphx8XU",
      "name": "Shoes",
      "children": [{
        "_id": "PxX4EYMYVDOphx8XU",
        "name": "Black Shoes"
      }]
    }, {
      "_id": "gUHcdTuPxXhauIWaZ",
      "name": "Shirts"
    }]
  }, {
    "_id": "svcdrpPybHJf0KiBi",
    "name": "Flowers",
    "children": [{
      "_id": "gdEk85byoRCWxStTf",
      "name": "Red Flowers"
    }]
  }]
}]

1 个答案:

答案 0 :(得分:0)

您需要以递归方式遍历对象并匹配<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:[yourapp]="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/menu_add_size" android:title="@string/menu_add_item" android:orderInCategory="10" [yourapp]:showAsAction="always" android:icon="@android:drawable/ic_menu_add" /> ,然后返回父对象。一个例子可能是。

&#13;
&#13;
_id
&#13;
var walk = returnExports;
var x = [{
  "_id": "v4jdHchuogyumed7f",
  "name": "products",
  "children": [{
    "_id": "fDE1kyR081Y44aO7h",
    "name": "Clothes",
    "children": [{
      "_id": "l464EYMYVDOphx8XU",
      "name": "Shoes",
      "children": [{
        "_id": "PxX4EYMYVDOphx8XU",
        "name": "Black Shoes"
      }]
    }, {
      "_id": "gUHcdTuPxXhauIWaZ",
      "name": "Shirts"
    }]
  }, {
    "_id": "svcdrpPybHJf0KiBi",
    "name": "Flowers",
    "children": [{
      "_id": "gdEk85byoRCWxStTf",
      "name": "Red Flowers"
    }]
  }]
}];
var find = 'PxX4EYMYVDOphx8XU';
var children;
var parent;
walk(x, Object.keys, function(value, prop, object, depth) {
  if (prop === 'children' && Array.isArray(value)) {
    children = value;
    walk.STOP;
  }
  if (prop === '_id' && value === find) {
    parent = children.find(function(obj) {
      return object._id === find;
    });
    return walk.BREAK;
  }
});
console.log(parent);
&#13;
&#13;
&#13;

https://www.npmjs.com/package/object-walk-x如果您不想编写自己的对象漫步者。