gpt4 book ai didi

node.js - mongoose findbyidandupdate 刚刚传递了值

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:21 25 4
gpt4 key购买 nike

所以我只想更新传递的对象的值。

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

我现在的函数将使发布请求中未定义的任何字段为空。
例如,如果我的对象定义了所有字段,并且我尝试仅更新名称:

{
"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": []
}

有什么方法可以执行此更新而不必传递所有其他字段吗?

最佳答案

当您未发送所有参数时,它们被设置为 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);
});

关于node.js - mongoose findbyidandupdate 刚刚传递了值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39060526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com