简体   繁体   中英

How to get Object ID after update the document using Node.js and MongoDB

I am updating my document using Node.js and I need to get that document id after updated. My code is below:

 var udata={
            name:name,
            company:company,
            position:position,
            mobile:mobile,
            email: email,
            landline: landline,
            url:url,
            postcode:postcode,
            address:address,
            profiletext:profiletext,
            biography:biography,
            updated_date:updateDate,
            file:file
        }
    db.f_card_details.update({userid:userid},{$set:udata},function(error,docum){
        if (!error) {
            if (docum) {
                console.log('document',docum);
                var edata=[{"id": docum._id}];
                var data={"statusCode": 200,"data":edata ,"message": "Your card details has been updated successfully"};
                res.send(data);
        }
}else{
            var data={"statusCode": 404,"error": "Not Found","message": "Your card details could not updated"};
            res.send(data);
}
                        })

Here I am not getting that document object id after update.

From mongodb.com this link -

"The update() method returns a WriteResult object that contains the status of the operation. Upon success, the WriteResult object contains the number of documents that matched the query condition, the number of documents inserted by the update, and the number of documents modified:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) "

Try using findOneAndUpdate

It will return old document, but you can set the returnNewDocument : true flag to make it return the new one.

So your code would be something like:

db.f_card_details.findOneAndUpdate({userid:userid},{$set:udata},function(error,docum){

    console.log(docum._id);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM