2017-05-24 24 views
0

我知道我能做到使用$set更新:如何在MongoDB中/貓鼬使用其以前的值更新字段

Contact.update({ 
    _id: request.id 
}, { 
    $set: { name: newNameValue } 
}, { 
    upsert: false 
}, function(err) { ... }); 

但在這種情況下,強似newNameValue,我想用之前的name值來計算新的值。比方說,我想大寫舊名稱,如:

Contact.update({ 
    _id: request.id 
}, { 
    $set: { name: $old.name.toUpperCase() } 
}, { 
    upsert: false 
}, function(err) { ... }); 
+0

這很可能是無法實現的一個語句來做到這一點。 – Mikey

回答

0

據我所知,這是不可能的。你需要找到並更新

Contact 
    .find({ 
     _id: request.id 
    }) 
    .exec(function(err, data) { 
      if (err) { 
       return ...; 
      } 
      Contact.findByIdAndUpdate(request.id, { 
       $set: { 
        name: data.name.toUpperCase() 
       } 
      }, { 
       new: true 
      }, function(err, doc) { 
       if (err) return ...; 
       console.log(doc) 
      }); 
     } 
1

我覺得這已經在這裏找到答案:How to add new data to current string in MongoDB?,所以,請檢查有關更詳細的答案,但無論如何,總之,你不能做到這一點與一個查詢。

做使用Mongoose,如圖this official Mongoose example方式:

Contact.findById(request.id, (err, contract) => { 
    if (err) return handleError(err); 

    contract.name = contract.name.toUpperCase(); 

    contract.save((err, contractContract) => { 
     if (err) return handleError(err); 

     ... 
    }); 
});