2017-08-23 1 views
0

Ich aktualisiere mein Dokument mit Node.js und ich muss diese Dokument-ID nach der Aktualisierung erhalten. Ich erkläre meinen Code unten.Wie bekomme ich die Objekt-ID nach der Aktualisierung des Dokuments mit Node.js und MongoDB

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

Hier bekomme ich nicht das Dokument object id nach dem Update.

+0

MongoDB neues _id jedes Mal, wenn Sie von –

+0

MongoDB _id auf jedes Objekt der Sammlung erstellen erstellen, wenn Sie es nach Stichwort neu erstellen. var user = new User ({...}) –

Antwort

0

Von mongodb.com this link -.

„Die update() Methode gibt ein Write Objekt, das den Status des Vorgangs enthält Bei Erfolg des Write Objekt der Anzahl der Dokumente enthält, die die Abfragebedingung angepasst, die Anzahl der Dokumente durch das Update eingeführt und die Anzahl der Dokumente geändert:

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

+0

So, wie man die 'Objekt-ID 'bekommt. – satya

+0

Ich fand eine ähnliche Frage - https://stackoverflow.com/questions/24747189/update-and-return-document-in-mongodb Die Antwort ist - 'collection.findOneAndUpdate()' –

0

Versuchen findOneAndUpdate

mit 210

Es wird das alte Dokument zurückgeben, aber Sie können das Flag returnNewDocument : true so einstellen, dass es das neue zurückgibt.

So würde Ihr Code so etwas wie:

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

    console.log(docum._id); 
}) 
Verwandte Themen