获取所有相关的子元素

时间:2019-06-04 10:13:11

标签: javascript node.js object

我在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是2的父级,2是3的父级,而4是5的父级。如何获取上面的所有元素(5个元素),但是只知道1的_id(25268)?

1 个答案:

答案 0 :(得分:0)

使用给定的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);
  });
});
相关问题