默认不在mongoose中工作保存 - 不保存字段

时间:2015-01-30 17:40:15

标签: node.js mongodb mongoose

我有一个包含以下定义字段的架构:

range: {type: Number, default: 100000, min: 1},

在控制器中我设置范围并保存:

function postPlacard(req, res) {

    // Create a new instance of the Placard model
    var placard = new Placard();

    ...

    placard.range = req.body.range;

    ...

    placard.save(function(err) {
      if (err)
        res.send(err);

      res.json({ message: 'Placard added!', data: placard });
  });
}

如果我在表单中提交没有范围的POST,则会出现问题。在这种情况下,没有范围字段保存到文档中。这显然意味着范围小于其最小值。

我希望在保存之前未定义范围,然后在保存期间应该应用默认值。

导致保存文档中缺少范围的原因是什么,以及如何更正?

由于

1 个答案:

答案 0 :(得分:5)

您遇到此错误,因为即使缺少placard.range字段,您也会分配到req.body.range。这会覆盖range中设置的默认new Placard()值。

对您的作业进行限定,以便只有在字段存在时才会使用以下内容:

if (req.body.range !== undefined) {
    placard.range = req.body.range;
}