Node.js+MongoDB:插入一个并返回新插入的文档

我想知道是否有办法插入新文档并一次性返回

这是我目前正在使用的:

db.collection('mycollection').insertOne(选项、函数(错误、响应){
...
});

更新2021:这种方法不再适用于MongoDB驱动程序4.x。insertOne的返回结果只包含一个ID和确认标志:https://mongodb.github.io/node-mongodb-native/4.1/interfaces/InsertOneResult.html

有了这一变化,就无法实现所需的行为。您应该执行另一个DB请求,或者合并返回的insertId和原始对象数据


响应结果包含有关命令是否成功以及插入的记录数的信息

如果要返回插入的数据,可以尝试response.ops,例如:

db.collection('mycollection').insertOne(文档、函数(错误、响应){
如果(错误){
log('插入时出错');
//返回
}否则{
console.log('inserted record',response.ops[0]);
//返回
}
});

insertOne的官方文档

http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne

回调类型:

http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpCallback

结果类型:

http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpResult

发表评论