【问题标题】:How to find document through nested children id如何通过嵌套的子 ID 查找文档
【发布时间】:2016-09-10 19:44:59
【问题描述】:

我的文档中有嵌套的孩子我想找到文档任何孩子._id 我的文件如下所示。

例如:

我想要这个children._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"
    }]
  }]
}]

【问题讨论】:

  • 我没有使用 Array#findIndex,
  • 你想要嵌套对象中的最后一个子 _id
  • 看起来你需要递归遍历对象并测试_id
  • 不,任何 'children._id` 都不依赖于职位。
  • 所有来自对象的children._id

标签: javascript node.js mongodb algorithm


【解决方案1】:

您需要递归遍历对象并匹配_id,然后返回父对象。一个例子可能是。

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);
<script src="https://rawgithub.com/Xotic750/object-walk-x/master/lib/object-walk-x.js"></script>

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

【讨论】:

    猜你喜欢
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 2017-10-05
    • 2019-07-16
    相关资源
    最近更新 更多