我试图在一个循环中多次更新集合,但每次我得到 oldRight 的值都没有改变它总是给出第一个值。
我使用嵌套集模式将主题存储在 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]);
}
});
}
}