Mongoose findByIdAndUpdate()查找/返回对象,但不更新

时间:2017-12-13 09:52:40

标签: node.js mongodb mongoose mongoose-schema

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

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...}

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

Schema看起来像这样:

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

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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 }
);