Mongoose填充未保存的对象

时间:2017-09-15 02:05:14

标签: node.js rest mongoose

我的解释是否正确?有没有办法做到这一点?

在我阅读other postsMongoose doc时,新创建的文档只有在保存到数据库后才能真正显示为已填充。

这种行为似乎足以保持数据的一致性,但是在首先停止,然后保存,然后检索它然后填充它然后显示新对象似乎有很多开销。

我的代码在router.js文件中,即:

                    if(favorites == null) { 
                        var newFavorite = new Favorites({
                            postedBy: req.decoded._doc._id,
                            dishes: req.params.dishId
                        });

                        newFavorite.save(function(err) {
                            if(err) throw err;
                            console.log('Favo created!');
    //pseudocode below-------------------------------------------
                            newFavorite
                                .populate('postedBy')//I need to populate this..
                                .populate('dishes')//and this so I can show the referenced docs in their entirety in the response which is...
                                .exec(function (err, user) {
                                    //handle error
                                })
    //pseudocode above-------------------------------------------
                        res.json(newFavorite)//---populated object here!
                        ;
                    });
                } else {

0 个答案:

没有答案