我在使用Node.js和mongodb。无法使用findAndModify更新数据库
var mongo = require("mongodb").MongoClient;
var url = process.env.MLAB_URI;
mongo.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established');
var sequence = db.collection('sequence')
//Find and modify the sequence counter.
var obj = sequence.findAndModify({
query: {_id: 1},
update: { $inc: {seq: 1}},
new: true
});
console.log(obj);
sequence.find({_id:1}).toArray(function(err,res){
if(err)
console.log(err);
else
console.log(res)
});
db.close();
}
});
但上面的代码未更新数据库,并返回的obj
输出为Promise { <pending> }
。 完整的输出是
Connection established
Promise { <pending> }
[ { _id: 1, seq: 0 } ]
我需要更新值并检索对象。有没有办法做到这一点? 在此先感谢!
你的意思是 “序列” 前值更新为14呢?你正在尝试增加seq。它似乎增加了价值。 – notionquest
是的,甚至在14之前。它只适用于更新命令。 –