Node.js + MongoDB:插入一个并返回新插入的文档 [英] Node.js + MongoDB: insert one and return the newly inserted document
问题描述
我想知道是否有一种方法可以一次性插入新文档并将其返回.
I'm wondering if there is a way to insert new document and return it in one go.
这是我当前正在使用的:
This is what I'm currently using:
db.collection('mycollection').insertOne(options, function (error, response) {
...
});
推荐答案
response
结果包含有关命令是否成功以及插入的记录数的信息.
The response
result contains information about whether the command was successful or not and the number of records inserted.
如果要返回插入的数据,可以尝试response.ops
,例如:
If you want to return inserted data, you can try response.ops
, for example:
db.collection('mycollection').insertOne(doc, function (error, response) {
if(error) {
console.log('Error occurred while inserting');
// return
} else {
console.log('inserted record', response.ops[0]);
// return
}
});
insertOne
的官方文档:
http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne
callback
类型:
http://mongodb.github.io /node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpCallback
result
类型:
http://mongodb.github.io /node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpResult
这篇关于Node.js + MongoDB:插入一个并返回新插入的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!