简体   繁体   English

在nodejs循环中每次更新后如何获取文档的新值?

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

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.我试图在一个循环中多次更新集合,但每次我得到 oldRight 的值都没有改变它总是给出第一个值。

I'm storing topics in mongodb using nested sets pattern.我使用嵌套集模式将主题存储在 mongodb 中。

 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]); } }); } }

Working with the database is an asynchronous function, you can't do it in a normal loop.使用数据库是异步的function,你不能在正常循环中进行。 And change var to let , using var is a bad practice leading to many problems.并且将var更改为let ,使用var是一种不好的做法,会导致很多问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM