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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40766654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:50:13  来源:igfitidea点击:

Node.js + MongoDB: insert one and return the newly inserted document

node.jsmongodb

提问by evilReiko

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) {
    ...
});

回答by Shaishab Roy

The responseresult contains information about whether the command was successful or not and the number of records inserted.

response结果包含有关命令是否成功与否和插入的记录数量的信息。

If you want to return inserted data, you can try response.ops, for example:

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

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 
    }
});

Official documentation for insertOne:

官方文档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#insertOne

The callbacktype:

callback类型:

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#~insertOneWriteOpCallback

The resulttype:

result类型:

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

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

回答by Naveen Kumar V

The following code worked for me, in MongoDB version 2.2.33.

以下代码对我有用,在MongoDB 版本 2.2.33 中。

db.collection("sample_collection").insertOne({
   field1: "abcde"
}, (err, result) => {
   if(err) console.log(err);
   else console.log(result.ops[0].field1)
}

回答by mrunde

You could use mongooseto do this. With the savemethod you can insert a document and return it on success. Here is an example from the mongoose documentation:

你可以使用猫鼬来做到这一点。使用该save方法,您可以插入文档并在成功时返回它。这是猫鼬文档中的一个示例:

product.save(function (err, product, numAffected) {
  if (err) {
    // Handle error...
  } else {
    // Do something with the returned document...
  }
})

回答by Volodymyr Synytskyi

You could use mongojsto do this.

你可以使用mongojs来做到这一点。

db.collection('mycollection').save(doc, function(error, response){
  // response has _id
})