简体   繁体   中英

Return Inserted Document in MongoDb ( Node.js )

I need to insert one document to MongoDB and return the newly inserted document. I used db.collection('collection__name').insertOne('data to be inserted').then((res)=>{ res.send(res.ops[0]) })

ERROR: ops is not defined.

insertOne only returns the _id of the document inserted and not the whole document☹ but Earlier it used to return the whole document. I used mongoclient and not mongoose and In mongoose it returns the whole doc but I don't like to work with mongoose.

They removed the ops field since mongo 4.0, you can find the schema here: https://mongodb.github.io/node-mongodb-native/4.0/interfaces/insertoneresult.html#insertedid

I just looked up the source code of mongoose and they are actually calling findOne based on the insertedId field:

    const promise = collection.insertOne({ foo: 'bar' }, {})
      .then(result =>
        collection.findOne({ _id: result.insertedId })
      ).then(doc => {
        assert.strictEqual(doc.foo, 'bar');
      });

( https://github.com/Automattic/mongoose/blob/80245edf5aeab304411681035f7f4153dbd2b692/test/collection.test.js#L50 ).

It seems as the only solution is to either use an old library version (without typescript) or call findOne with the returned id field. I just had the same problem and added the additional findOne call, cause I didn't want to give up typescript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM