Bruno Henrique
Bruno Henrique

Reputation: 141

Mongodb return updated object with populate

So I'm new to mongodb and i'm trying to insert a new comment which has a field user(ref by id) to a post and return the updated post.The problem is how can I return it with only one query with populate option? here's my code working but its kind slow, not sure if its because the 2 'find' queries. Is there another way to do it with only one populate query?

       var newComment = {
            comment:req.body.text,
            isEdit:false,
            user:req.body.user
        };

        comments.create(newComment,function(err,commentCreated){
            post.find({_id:req.params.postId},function(err,postFound){
                if(err){
                    throw err;
                } else {
                    postFound[0].comments.push(commentCreated);
                    post[0].save(function(){
                      post.find({_id:req.params.videoId}).populate({path:'comments',populate:{path:"user",model:"users"}})
                      .exec(function(err,data){
                        if(err){
                          throw err;
                        }
                        else{
                          res.json(data);
                        }
                  })

               });

           });

Upvotes: 1

Views: 3264

Answers (1)

chridam
chridam

Reputation: 103365

Use findByAndUpdate() which returns a Query that you can populate. Call exec() on the function to return a Mongoose Promise, thus you can convert the current code to

var postId = req.params.postId;
var newComment = new Comment({
    comment: req.body.text,
    isEdit: false,
    user: req.body.user
});

newComment.save().then(function(comment){
    Post.findByIdAndUpdate(
        postId,
        { "$push": { "comments": comment._id } },
        { "new": true, "upsert": true }
    )
    .populate({
        "path": "comments",
        "populate": {
            "path": "user",
            "model": "users"
        }
    })
    .exec();
})
.then(function(data) { res.json(data); })
.catch(function(err) { throw err; });

Upvotes: 2

Related Questions