Karan
Karan

Reputation: 345

Nodejs+Mongoose : find and update

I'm trying to search for a document in my mongo database then using the found document data to search another document and then update both. First document is to be saved after the second document is found.

But with my code the first document saves but doesnot saves updated data

My code :

 var posts = {};
 Posts.findOne({'url': req.body.url}, function(err, data){
            posts = data;
            //console.log(data);
            Comments.findOne({'bucket': posts.bucket}, function(err, data){
                var comment= data;
                if(data.count>10){
                   posts.bucket = posts.bucket +1;
                   comment.bucket = comment.bucket +1;
                }
                comment.save(function(err, data){
                    if(err)
                        throw err;
                });
            });
            posts.save(function(err, data){
                if(err)
                    throw err;
                res.json(data);
            });
        });

I observed that whatever changes is done in posts variable in Comments.findOne({...}) it remains local to it and doesnot effect outer posts varible, but it is just declared once. so how can i do this. Is something wrong in code? How do I do this!

Upvotes: 1

Views: 1516

Answers (1)

Marwen Trabelsi
Marwen Trabelsi

Reputation: 4257

First document is to be saved after the second document is found.

In your code you're saving the comment and the post in a parallel manner, you need to save the post after saving the document :

var posts = {};
 Posts.findOne({
     'url': req.body.url
 }, function(err, data) {
     posts = data;
     //console.log(data);
     Comments.findOne({
         'bucket': posts.bucket
     }, function(err, data) {
         var comment = data;
         if (data.count > 10) {
             posts.bucket = posts.bucket + 1;
             comment.bucket = comment.bucket + 1;
         }
         comment.save(function(err, data) {
             if (err)
                 throw err;

             posts.save(function(err, data) {
                 if (err)
                     throw err;
                 res.json(data);
             });
         });
     });

 });

Another important remark: you're creating a callback hell which leads to unknown behavior later. Please use async or promises instead of nesting callbacks.

Upvotes: 1

Related Questions