how to properly use find and update in mongoDB?

Viewed 51

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 Answers

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})     
Related