【问题标题】:Get all of related children element获取所有相关子元素
【发布时间】:2019-06-04 10:13:11
【问题描述】:

我在数据库中有很多记录,例如下面是 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 的父级,4 是 5 的父级。如何获取上述所有元素(5 个元素)但只知道 _id of 1 (25268)?

【问题讨论】:

  • 您的预期输出是什么?
  • 我们有元素 1(25268) 的 _id 并且输出将得到 5 个元素。

标签: javascript node.js object


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-09-07
    • 2019-07-10
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 2013-09-11
    • 2016-11-06
    • 2014-10-08
    • 1970-01-01
    相关资源
    最近更新 更多