Express 和 Mongoose - 无法更新对象

Express and Mongoose-failing to update an object

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

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 模式中定义,但在数据库中的对象中不存在)时,它失败了。意思是,没有错误,但没有添加新字段。

有什么想法吗?

根据mongoose documentation of findByIdAndUpdate

  • new: bool - return 修改后的文档而不是原始文档。默认为 false

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


您将 new 误认为是 upsert


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