所以我想只更新传递的对象的值。
Event.findByIdAndUpdate(req.body.id, {
$set: {
name: req.body.name,
narrative: req.body.narrative,
startdate: req.body.startdate,
enddate: req.body.enddate,
site: req.body.site
}
}, {new: true},
function(err, Event) {
if (err) throw err;
res.send(Event);
});
我的函数现在将使post请求中未定义的任何字段为空 例如,如果我的对象已定义了所有字段,我尝试使用以下命令更新名称:
{
"id": "57b8fa4752835d8c373ca42d",
"name": "test"
}
将导致:
{
"_id": "57b8fa4752835d8c373ca42d",
"name": "test",
"narrative": null,
"startdate": null,
"enddate": null,
"site": null,
"__v": 0,
"lastupdated": "2016-08-21T00:48:07.428Z",
"sponsors": [],
"attendees": []
}
有没有办法执行此更新而不必通过所有其他字段?
答案 0 :(得分:2)
当您不发送所有参数时,将其设置为null
的原因是因为您的更新中包含null
值。
防止这种情况的唯一方法是在进行修改之前检查并确保设置变量。
类似的东西:
var modifications = {};
// Check which parameters are set and add to object.
// Indexes set to 'undefined' won't be included.
modifications.name = req.body.name ?
req.body.name: undefined;
modifications.narrative = req.body.narrative ?
req.body.narrative: undefined;
modifications.startdate = req.body.startdate ?
req.body.startdate: undefined;
modifications.enddate = req.body.enddate ?
req.body.enddate: undefined;
modifications.site = req.body.site ?
req.body.site: undefined;
Event.findByIdAndUpdate(
req.body.id,
{$set: modifications},
{new: true},
function(err, Event) {
if (err) throw err;
res.send(Event);
});