Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating document with id from other action using previous id (nodejs & mongodb)

I have something I cant find a solution for …
Let me explain in in short:
Step 1. Create a new collection in document A
Step 2. Use this id and create a new collection in document B
Step 3. Update collection from step 1 with the id from step2

In nodejs:

DocumentA.create({something})
.then((result)=>{
DocumentB.create({x : result.id})})
.then((result2) => { 
DocumentA.updateOne({_id: ?????}, {$set:{y: result2.id}})

And completely stuck here (at the ????) as I cannot use ‘result’ anymore.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would encourage switching to using async/await but you can do something like this:

DocumentA.create({something})
.then((result)=>{
   return Promise.All([
     Promise.resolve(result), 
     DocumentB.create({x : result.id})
   ])
.then(([result, result2]) => { 
  DocumentA.updateOne({_id: result._id, {$set:{y: result2.id}
}) 

The primary thing is to use return <Promise> to pass to the next .then

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading