Joshua Bisanda
Joshua Bisanda

Reputation: 1

Is there a way to return a document right after insertion?

I'm currently trying to return the document I just added to a collection to display it in real time on my homepage.

I followed a solution I found here: link to 2018 solution. But this solution doesn't seem to work for the latest node.js and MongoDb versions.

I'm essentially trying to do the same thing the person in that post was trying to do but I get the following error:

res.json (info.ops[0]);
TypeError: Cannot read property '0' of undefined

Here's my code for reference:

app.post('create-item', (req, res) => {
dB.collection('items').insertOne({text: req.body.text}, (err, info) => {
res.json(info.ops[0]);});});

Upvotes: 0

Views: 292

Answers (1)

Takis
Takis

Reputation: 8695

When we use insertOne with the Nodejs driver 4 (the latest) we get a response like
{"acknowledged" : true, "insertedId" : #object[ObjectId 61105622b633ecabf3706782]}

Save the document to a variable before inserting it.
If the document had _id, check if it was inserted and get the document from the variable.
If the document didn't had _id, check if it was inserted and get the _id also from the response, and add that _id to the document you have in the variable.

Maybe i am missing something but the above is simple to do, if this is what you need.

Upvotes: 1

Related Questions