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

标签 node.js mongodb

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

            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/

相关文章:

mongodb - 如何在 Mongodb 中拉出嵌套对象?

javascript - 如何在 Mongoose 中使用分组依据和查找?

python - 如何使用 pymongo 写入/读取两个不同的 mongo 服务器(具有不同版本的 mongo 2.4 和 3.0.3)

angular - mongodb中看不到数据

javascript - 如何将事件处理程序附加到 native Node.js 模块中的进程导出?

node.js - Express session 和 PassportJS 之间的区别

node.js - 在 MongoDB 中的多个字段上使用 $in

javascript - 安装和使用 React

node.js - 无法请求全局模块

linux - Mongodb - 如何重启你刚刚在 Linux 中杀死的 mongodb?