簡體   English   中英

使用Node.js和MongoDB更新文檔后如何獲取對象ID

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

我正在使用Node.js更新我的文檔,更新后需要獲取該文檔ID。 我的代碼如下:

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

在這里,更新后我沒有得到那個文檔object id

來自mongodb.com的此鏈接 -

“ update()方法返回一個包含操作狀態的WriteResult對象。成功后,該WriteResult對象將包含與查詢條件匹配的文檔數,更新插入的文檔數以及已修改的文檔數。 :

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

嘗試使用findOneAndUpdate

它將返回舊文檔,但是您可以設置returnNewDocument : true標志以使其返回新文檔。

因此,您的代碼將類似於:

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

    console.log(docum._id);
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM