如何使用MongoDB/Mongoose中的先前值更新字段
我知道我可以使用如何使用MongoDB/Mongoose中的先前值更新字段,mongodb,mongoose,Mongodb,Mongoose,我知道我可以使用$set进行更新: Contact.update({ _id: request.id }, { $set: { name: newNameValue } }, { upsert: false }, function(err) { ... }); 但是在本例中,我不想传递newNameValue,而是想使用前面的name值来计算新值。假设我想把旧名字大写,比如: Contact.update({ _id: request.id }, { $
$set
进行更新:
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) { ... });
据我所知这是不可能的。您需要查找并更新
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)
});
}
我想这已经在这里得到了回答:,所以,请检查一下,以获得更详细的答案,但无论如何,简言之,您不能通过一个查询来实现这一点 使用
Mongoose
执行此操作的方法,如所示:
用一句话很可能做不到。
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);
...
});
});