Node.js + MongoDB:插入一个并返回新插入的文档 [英] Node.js + MongoDB: insert one and return the newly inserted document

查看:58
本文介绍了Node.js + MongoDB:插入一个并返回新插入的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以一次性插入新文档并将其返回.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆