【问题标题】:Express and Mongoose-failing to update an objectExpress 和 Mongoose 无法更新对象
【发布时间】:2018-08-15 10:15:18
【问题描述】:

我正在尝试通过为其分配一个在架构中定义的新字段来更新对象,如下所示:

exports.updatePlot = async (req, res) => {
    let modifications = {};
    modifications = Object.assign(modifications, req.body.props);
    const id = modifications.id;
    try {
        const updatedPlot = await Plot.findByIdAndUpdate(
            id,
            { $set: modifications },
            { new: true }
        );
        console.log(('updated  plot saved:', updatedPlot));
        res.json({
            updatedPlot
        });
    } catch (e) {
        console.log('error', e);
        return res.status(422).send({
            error: { message: 'e', resend: true }
        });
    }
};

这在我修改现有字段时有效。但是,当我尝试添加一个新字段(在 Mongoose 模式中定义,但在数据库中的对象中不存在)时,它会失败。意思是,没有错误,但没有添加新字段。

有什么想法吗?

【问题讨论】:

  • 我认为你不需要使用 $set。 Plot.findByIdAndUpdate(query,body,options)

标签: javascript node.js express mongoose mongoose-schema


【解决方案1】:

根据mongoose documentation of findByIdAndUpdate

  • 新:bool - 返回修改后的文档而不是原始文档。默认为假

  • upsert: bool - 如果对象不存在则创建它。默认为 false。


您将 new 误认为 upsert


此外,正如@Rahul Sharma 所说并查看 mongoose 文档示例,您不需要使用 $set

【讨论】:

  • 我希望返回修改后的文档。
  • 所以同时使用 new 和 upsert。喜欢{ new: true, upsert: true }
  • 如果新对象不存在,我不想创建它。
猜你喜欢
  • 1970-01-01
  • 2018-06-04
  • 2021-01-21
  • 1970-01-01
  • 2019-05-17
  • 1970-01-01
  • 2019-03-25
  • 1970-01-01
  • 2011-10-21
相关资源
最近更新 更多