首页 > 解决方案 > findByIdAndUpdate 覆盖现有值

问题描述

面临一个小问题,每当我尝试更新“评论”属性时,它会自动覆盖旧属性,不会将下一个值添加到数组中。尝试了许多选项,例如添加 $set 参数作为选项,删除它,添加覆盖:false,但没有成功。一直在看文档,但感觉好像我缺少了什么,甚至文档也帮不了我。

我的模型:

const mongoose = require("mongoose");


const TicketSchema = new mongoose.Schema({
    title: {
        type: String,
        minlength: 5,
        maxlength: 50,
        required: [true, "Please validate title"]
    },
    description: {
        type: String,
        minlength: 10,
        maxlength: 200,
        required: [true, "Please validate description"]
    },
    comments: {
        type: Array,
        default: []
    },
    status: {
        type: String,
        enum: ["in progress", "resolved", "pending"],
        default: "pending",
    },
    priority: {
        type: String,
        enum: ["regular", "medium", "high"],
        default: "regular"
    },
    createdBy: {
        type: mongoose.Types.ObjectId,
        ref: "User",
        required: [true, "Please provide user"],
    }
}, {
    timestamps: true,
});

module.exports = mongoose.model('Ticket', TicketSchema);

我的控制器:

const updateUser = async (req, res) => {
    const {
        body: {username, email, firstname, lastname, country, password, comments},
        params: {
            id: employeeId
        }
    } = req;

    const user = await User.findByIdAndUpdate(employeeId, req.body, {
        $set: {
            comments: req.body.comments
        }
    }, {
        new: true, runValidators: true, upsert: true
    }).select(["-password"]);

    // Don't allow IT users to change credentials for IT and ADM users.
    if (user.type.startsWith("IT") || user.type.startsWith("ADM")) throw new NotFoundError(`No user with id ${employeeId}`);

    if (!user) throw new NotFoundError(`No user with id ${employeeId}`);

    res.status(StatusCodes.OK).json({user});

};

标签: node.jsmongodbexpressmongoose

解决方案


您可能想要使用$push运算符而不是$set.

假设req.body.comments是一个带有注释的数组,你可以$each用来构造这样的东西:

const user = await User.findByIdAndUpdate(employeeId, req.body, {
    $push: {
        comments: { $each: req.body.comments }
    }, {
        new: true, runValidators: true, upsert: true
    }
}).select(["-password"]);


推荐阅读