我正在尝试使用findByIdAndUpdate在猫鼬中更新“ Board”模型,并且该模型在模型上具有一个“ items”(即对象)数组。我可能不太了解猫鼬,但由于某种原因,数组中的每个项目都会随董事会一起生成一个ID。这不是问题,实际上很方便,但是,在执行findByIdAndUpdate之后,每个项目的ID都已更改。这让我感到非常惊讶,我真的以为他们会保持不变。这可能是由于更新数组中的所有项目引起的吗?猫鼬也许只是扔掉整个数组并在更新时创建一个新数组(也许有人知道吗?)。无论如何,我的问题是:有没有一种方法可以在不更改这些ID的情况下更新模型。我真的希望他们保持一致。我用于更新的代码是
exports.updateBoard = asyncHandler(async (req, res, next) => {
let board = await Board.findById(req.params.id);
if (!board) {
return next(new CustomError(`Board not found with id of ${req.params.id}`, 404));
}
// Authorize user
if (board.user.toString() !== req.user.id) {
return next(new CustomError(`User ${req.user.id} is not authorized to update board ${board._id}`, 401));
}
req.body.lastUpdated = Date.now();
board = await Board.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true })
.select('-__v')
.populate({
path: 'user',
select: 'name avatar',
});
// 200 - success
res.status(200).json({ success: true, data: board });
});
和BoardSchema:
const BoardSchema = new Schema(
{
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: [true, 'Board must have a user'],
},
name: {
type: String,
required: true,
trim: true,
},
description: {
type: String,
required: false,
trim: true,
},
items: [
{
title: {
type: String,
required: true,
trim: true,
},
description: {
type: String,
required: false,
trim: true,
},
dateCreated: {
type: Date,
default: Date.now,
},
lastUpdated: {
type: Date,
default: Date.now,
},
},
],
columns: [
{
name: {
type: String,
required: true,
},
index: {
type: Number,
required: true,
},
show: {
type: Boolean,
required: true,
},
},
],
dateCreated: {
type: Date,
default: Date.now,
},
lastUpdated: {
type: Date,
default: Date.now,
},
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);