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

后端 未结 6 1313
谎友^
谎友^ 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:29

    Posting this as this might be helpful for someone. You can find the updated object like this:

    await req.db
        .collection('users')
        .insertOne({ email, password: hashedPassword, name  })
        .then(({ ops }) => ops[0]);
    
    0 讨论(0)
  • 2021-01-01 12:32

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

    db.collection("sample_collection").insertOne({
       field1: "abcde"
    }, (err, result) => {
       if(err) console.log(err);
       else console.log(result.ops[0].field1)
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-01 12:42

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

    product.save(function (err, product, numAffected) {
      if (err) {
        // Handle error...
      } else {
        // Do something with the returned document...
      }
    })
    
    0 讨论(0)
  • 2021-01-01 12:42

    Try This

    try {
        let collection = db.collection('collection_name'); let { ops: inserted } = 
        await collection.insertOne({ data: object });
        // can access array of inserted record like :
        console.log(inserted)
     } catch (error) {
        // log errors
     }
    
    0 讨论(0)
  • 2021-01-01 12:43

    You could use mongojs to do this.

    db.collection('mycollection').save(doc, function(error, response){
      // response has _id
    })
    
    0 讨论(0)
提交回复
热议问题