【问题标题】:Mongoose findByIdAndUpdate() finds/returns object, but does not updateMongoose findByIdAndUpdate() 查找/返回对象,但不更新
【发布时间】:2017-12-13 19:56:21
【问题描述】:

我正在尝试使用此代码查找和更新:

exports.updatePlot = async (req, res) => {
    let modifications = {};
    modifications.name = req.body.name;
    modifications.grower = req.body.props.grower;
    modifications.variety = req.body.props.variety;
    modifications.planted = req.body.props.planted;

    const id = req.body.props.id;

    try {
        const updatedPlot = await Plot.findByIdAndUpdate(
            id,
            { $set: { modifications } },
            { new: true }
        );
        res.json({
            updatedPlot
        });
    } catch (e) {
        return res.status(422).send({
            error: { message: 'e', resend: true }
        });
    }
};

我可以看到我的请求正文包含数据,我还可以看到 Mongoose 正在查找对象,但没有更新它,因为这是它作为更新图记录的内容:

{"_id":"id string here","name":"old name",...all other properties...}

我猜我的请求格式不正确?有人看到我的错误吗?

架构如下所示:

const plotSchema = new Schema(
    {
        name: String,
        ...other properties...
    },
    { bufferCommands: false }
);

const ModelClass = mongoose.model('plot', plotSchema);

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    您正在将您的 $set 对象设置为此:

    $set: {
        modifications: {
            name: 'xxx',
            grower: 'xxx',
            variety: 'xxx'
        }
    }
    

    但是,你想要的是:

    $set: {
        name: 'xxx',
        grower: 'xxx',
        variety: 'xxx'
    }
    

    尝试删除查询中modifications 上的花括号,如下所示:

    const updatedPlot = await Plot.findByIdAndUpdate(
        id,
        { $set: modifications },
        { new: true }
    );
    

    【讨论】:

      【解决方案2】:

      我认为问题出在请求中,试试这个:

      const updatedPlot = await Plot.findOneAndUpdate(
                  {_id: id},
                  modifications },
                  { new: true }
              );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-23
        • 2018-08-18
        • 2020-08-12
        • 2014-02-19
        • 2020-09-06
        • 2013-08-14
        • 2018-07-19
        相关资源
        最近更新 更多