簡體   English   中英

Mongoose - 在對象中填充對象

[英]Mongoose - Populate object in object

假設我有3 個模型

// Parent
const ParentSchema = new Schema({
    child: {
        type: ObjectId,
        ref: 'Child'
    },

    ...
});

// Child
const ChildSchema = new Schema({
    subChild: {
        type: ObjectId,
        ref: 'SubChild'
    },

    ...
});

// SubChild
const SubChildSchema = new Schema({
    name: String,
    ...
});

我在Parent上使用findOne ,我想在Child上使用populate ,但也在SubChildSubChild

Parent.findOne(options)
    .populate('child', 'subChild')
    // Trying to add another populate on subChild property like : .populate('<above_subChild>', 'name')
    .select('child')
    .exec(function (err, parent) {
        callback(err, parent.toJSON());
    })
;

有沒有辦法用populate做到這一點?


目前, parent.toJSON()返回:

{
    // Parent _id
    _id: XXX,
    child: {
        _id: XXX,
        subChild: <subChild_ObjectID>        
    }
}

下面是我想要通過在subChild屬性上添加另一個populatesubChild是:

{
    // Parent _id
    _id: XXX,
    child: {
        _id: XXX,
        subChild: {
            _id: XXX,
            name: XXX
        }
    }
}

這也將起作用:

Parent.findOne(options)
  .select('child')
  .populate('child.subChild')
  .exec(function(err, parent) {
    callback(err, parent.toJSON());
  });

參考populate的文檔,該查詢需要按如下方式構建以填充多個級別:

Parent.findOne(options)
  .populate({
    path: 'child',
    populate: {
      path: 'subChild'
    }
  })
  .select('child')
  .exec(function(err, parent) {
    callback(err, parent.toJSON());
  });

使用 mongoose 的populate方法需要注意的一件事是每個種群都需要一個單獨的查詢。 所以在這種情況下,雖然實現使用了一個顯式的findOne方法,但 mongoose 實際上是連續執行三個查詢。

這大致相當於(稍微偽編碼):

Parent.findOne().exec().then((parent) => ([
  parent,
  Child.findById(parent.child).exec()
])).then(([parent, child]) => ([
  parent,
  child,
  SubChild.findById(child.subChild).exec()
])).then(([parent, child, subChild]) => {
  child.subChild = subChild;
  parent.child = child;

  return parent;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM