how to get the new value of document after updating each time in nodejs loop?

72 views Asked by At

I'm trying to update collection many times in a loop but each time I get the value of oldRight not changed it gives the first value always.

I'm storing topics in mongodb using nested sets pattern.

     for(let name of level1) {

             console.log(name);
             var parent = 'root';

             getParentAndAddTopic(name, parent, function (err, topic) {
                 if (err) {
                     console.log(err);
                 }


                 var oldRight = topic.right;
                 console.log(oldRight);
                 db.topics.create({name: name, parent: 'root', left: oldRight, right: oldRight + 1}
                     , function (err, res) {
                         if (err) throw err;
                     });

                 db.topics.updateMany({right: {$gte: oldRight}}, {$inc: {right: 2}}
                     , function (err, res) {
                         if (err) throw err;

                     });
             });

           function getParentAndAddTopic(name, parent, callback) {
             db.topics.find({name: 'root'}, function (err, topics) {
                 if (err) {
                     callback(err, null);
                 } else {
                     callback(null, topics[0]);
                 }
             });
         }
     }

1

There are 1 answers

3
Yuriy Vorobyov On

Working with the database is an asynchronous function, you can't do it in a normal loop. And change var to let, using var is a bad practice leading to many problems.