node.js - 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});
};
解决方案
您可能想要使用$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"]);
推荐阅读
- javascript - Next.JS - 数据持久化
- android - 如何在 Detox 测试中使用深度链接默认打开 android 应用程序
- sh - 如何重用大括号扩展?
- ios - 在 iOS 上配置 Firebase 时,我应该更喜欢使用 APNs 密钥还是 APNs 证书
- firebase - firebase react native expo:这些文件都不存在
- java - 通用连接池已存在错误 (Oracle UCP)
- python - 为什么当我尝试使用对象 ID 打开链接时,它在 django 3.2 中不起作用?
- r - 使用 parSapply() 在 R 中使用并行化时如何导出具有修改值的全局变量
- php - 有什么功能可以修复或缩短蜿蜒的路径吗?
- sapui5 - sapui5 : typeERROR : i 不是构造函数