简体   繁体   English

获取所有相关的子元素

[英]Get all of related children element

I have many many record in db, below is 5 record for example 我在db中有很多记录,例如下面是5记录

/* 1 */
{
  "_id": 25268,
  "name": "Gạo",
  "parentid": -1
}
/* 2 */
{
  "_id": 25290,
  "name": "Japonica: Dẻo và mềm cơm",
  "parentid": 25268
}
/* 3 */
{
  "_id": 25291,
  "name": "Japonica: Dẻo và mềm cơm 1",
  "parentid": 25290
}
/* 4 */
{
  "_id": 25292,
  "name": "Japonica: Dẻo và mềm cơm 2",
  "parentid": 25290
}
/* 5 */
{
  "_id": 25293,
  "name": "Japonica: Dẻo và mềm cơm 3",
  "parentid": 25292
}

1 is parent of 2, 2 is parent of 3 and 4, 4 is parent of 5. How to get all element like above (5 elements) but just know _id of 1 (25268)? 1是2的父,2是图3和4的父,4是5.父如何获得所有元件像上述(5种元素),但只知道_id的1(25268)?

Using the given startId, it will fetch all its parent documents without querying find({}), 使用给定的startId,它将获取其所有父文档而不查询find({}),

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

var startId = 25268;

function getParent(dbo, parent) {
    parent.forEach(element => {
        console.log(element);
       dbo.collection("hello").find({parentid: element._id}) .toArray(function(err, result) {
           if (err) throw err;
           getParent(dbo, result);
       })
    });
}
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.collection("hello").find({parentid: startId}).toArray(function(err, result) {
    if (err) throw err;
    getParent(dbo, result);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM