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

后端 未结 6 1345
谎友^
谎友^ 2021-01-01 12:15

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\').i         


        
6条回答
  •  死守一世寂寞
    2021-01-01 12:39

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

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

    Official documentation for insertOne:

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

    The callback type:

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

    The result type:

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

提交回复
热议问题