how to properly use find and update in mongoDB?

I'm trying to add data to DB (which works fine) and I want the provided ID to be updated on other collection.

db.drivers.save(driverDetails, function(err, savedDrivedDetails){
            if(err){
                res.send(err)
            }
            //find the email/id and save the driver ID inside users db.
            dbUser.users.findOneAndUpdate({email:driverDetails.email}, //that driverDetails.email is valid
                {
                    driverId:savedDrivedDetails._id
                }
              
            )     
        })

I'm not sure how to make that call, should I need to make find() first and then update the data inside or make a function inside the update field db.collection.findOneAndUpdate( filter, update, options )

using nodejs. can anyone assist me?

Thanks in advance.

1 answer

  • answered 2022-05-04 16:38 Nir Yossef

    Instead of using a function as a parameter which is causing the problem because when this function is run dbUser.users is not defined,

    use this:

    const result = await db.drivers.save(driverDetails)
    
    dbUser.users.findOneAndUpdate({email:driverDetails.email}, {driverId:result._id})     
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum