簡體   English   中英

嵌套的貓鼬充滿了希望

[英]Nested mongoose populate with promises

我正在嘗試填充如下所示的模型:

var Org = new mongoose.Schema({
        _id: {type: String, unique:true}, //this will be the org code
        name: String,
        level: String,
        children: [{type: String, ref: 'Org'}]
    });

//Orgs have children orgs, which themselves can have children orgs at N levels

給定一個組織,我想填充它的孩子,以及它的孩子的孩子,等等。 我可以為N = 2個級別完成此操作,如下所示:

     req.Model.findOne({_id: id}).populate('children').exec(function(err, doc){
        if (err){
            return next(err);
        }
        req.Model.populate(doc, {path: 'children.children'}, function(err, doc){
            if(err){
                return next(err);
            }
            return res.json(doc);
        });
    });

幾個小時以來,即使在N = 2的情況下,我仍在嘗試使用Promise來完成上述任務。 我認為對於N = *級別,使用貓鼬具有內置實現的承諾會更清潔。

        req.Model.findOne({_id: id}).populate('children').exec()
        .then(function (doc){
            if(!treeView) {
                return doc;
            }
            return req.Model.populate(doc, {path: 'children.children'});
        })
        .then(function (doc){
            return res.json(doc);
        },function(err){
            return next(err);
        });

// treeView is a query string that lets me know that I need to populate the refs

我認為它應該如下工作:

  1. exec()返回一個promise,我在對then()的第一次調用時就開始處理
  2. 如果treeView為false,我返回doc,這被視為原始諾言的解決方案,因此調用了第二個then()處理函數。 這確實發生了。
  3. 如果treeView為true,則對Model.populate的調用將返回另一個Promise,第二個對then()的調用也將處理該Promise。

我收到此錯誤:

{
   "status": "error",
   "serverTimestamp": "2014-07-24T18:23:02.974Z",
   "message": "\"function\" == \"undefined\""
}

我知道它到達第二個then()的錯誤處理程序,因為我已經注銷到控制台進行驗證,但是我無法弄清楚為什么會這樣。 一旦使它生效,我將嘗試使其適用於N = *級,我想這將涉及遞歸地創建更多的Promise。 我在這里看到了很多相關的問題,但並不是我真正需要的。

任何幫助是極大的贊賞。

我能夠使用Mongoose模型返回的Mongoose許諾在MongooseJS v4.1中使嵌套的子文檔填充工作。 無需使用其他Promise庫。

var fuelOrderId = req.params.fuelOrderId;
fuelOrderModel.findById(fuelOrderId).populate('aircraftId')
.then(function(order){
    return fuelOrderModel.populate(order,
         {path: 'aircraftId.aircraftContacts', 
          model: 'aircraftContactModel'});
})
.then(function(result){
    res.json({
        fuelOrder: result,
        status: 1
    });
},function(err){
    console.error(err);
    res.json({err: err, status: 0});
})

編輯考慮使用.catch()代替錯誤的第二個函數。 mpromise現在支持.catch()

似乎現在找到了解決方案。

Q.ninvoke(doc, 'populate',{path: children.children})
.then(function(doc){
    return res.json(doc);
},function(err) {
    return next(err);
});

對我來說,很奇怪的是,我需要使用貓鼬Document.populate而不是Model.populate(doc ..),根據文檔的表現,貓鼬應該表現得非常相似,不同之處在於它返回了一個promise。 這是我不得不使用Q Promise API的原因之一,因為Document.populate不像Model.populate那樣返回Promise。 沒有常規的節點樣式回調,我無法使Model.populate工作,但是此解決方案可以滿足我的需求。 至於N = *級別,我只是根據需要遞歸調用Q.ninvoke多次,從而擴展了路徑,並且可以根據需要填充任意數量的級別。

暫無
暫無

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

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