Node.js 如何在mongodb中使用upsert选项从更新中获取ObjectID
是否可以使用Node.js 如何在mongodb中使用upsert选项从更新中获取ObjectID,node.js,mongodb,Node.js,Mongodb,是否可以使用upsert选项从update方法获取最后一个自动生成的ObjectID? 类似于mysql中的LAST\u INSERT\u ID() 下面是示例代码: /** * MongoDB ver. 2.4.9 * MongoDB NodeJS Driver ver. 1.3.23 */ var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://127.0.0.1:27017/l
upsert
选项从update
方法获取最后一个自动生成的ObjectID
?
类似于mysql中的LAST\u INSERT\u ID()
下面是示例代码:
/**
* MongoDB ver. 2.4.9
* MongoDB NodeJS Driver ver. 1.3.23
*/
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://127.0.0.1:27017/learning', function(err, db) {
var c = db.collection('testUpsert');
c.insert({a: true}, function(err, result) {
// Here I can reach `_id` field
console.dir(result); // object with id
});
c.update({ _id: undefined }, {a: false}, {upsert: true, w: 1}, function(err, result) {
// Any elegant way to fetch `_id` of new document here?
console.dir(result); // 1
});
});
findAndModify()不工作吗?是的!正是我需要的。谢谢,乔。下面的代码对我有用:
c.findAndModify({u id:undefined},[],{a:false},{upsert:true,new:true},函数(err,result){…}