Anand CA
Anand CA

Reputation: 23

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.

Upvotes: 0

Views: 3300

Answers (1)

itpropro
itpropro

Reputation: 304

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.

Upvotes: 5

Related Questions