Mongoose函数findByIdAndUpdate的工作方式为PUT而非PATCH



我是mongoose的新手,在尝试部分更新子文档时遇到了问题。尽管我使用了$set运算符,但它会重置其他字段,即使它们没有指定。我注意到,有时它似乎有效,有时却无效。我一直找不到图案。我需要简短的更新。

这是我的模式。

import { Schema, model } from "mongoose";
const Path = Schema({
original: { type: String, required: true },
tiny: { type: String },
small: { type: String },
medium: { type: String },
large: { type: String },
extra_large: { type: String },
});
const BusinessPictureSchema = Schema({
Path: {
type: Path,
required: true
},
is_valid: {
type: Boolean,
required: true,
default: false
},
date_validation: {
type: Date
}
}, {
timestamps: true
});

module.exports = model('BusinessPicture', BusinessPictureSchema)

我的测试功能:

async BusinessPicture() {
const input_create = {
Path: {
original: "original file",
tiny: "arhivo tiny"
}
}
const newBusinessPicture = new BusinessPicture(input_create);
await newBusinessPicture.save();
const input_update = {
Path: {
original: "new original file!!!"
}
}
await BusinessPicture.findByIdAndUpdate(newBusinessPicture.id, { $set: input_update });
return BusinessPicture;

// What i get
// {
//     "Path": {
//         "original": "original file",
//             "_id": {
//             "$oid": "6347a31784167896b62648e5"
//         }
//     },
//     "is_valid": false,
//         "createdAt": {
//         "$date": {
//             "$numberLong": "1665639182788"
//         }
//     },
//     "updatedAt": {
//         "$date": {
//             "$numberLong": "1665639191235"
//         }
//     },
//     "__v": 0
// }
// What i hope to find
// {
//     "Path": {
//       "original": "new original file!!",
//       "tiny": "arhivo tiny",          <----THISSSS
//       "_id": {
//         "$oid": "6347a4201829a87212b7c120"
//       }
//     },
//     "is_valid": false,
//     "createdAt": {
//       "$date": {
//         "$numberLong": "1665639452549"
//       }
//     },
//     "updatedAt": {
//       "$date": {
//         "$numberLong": "1665639456805"
//       }
//     },
//     "__v": 0
//   }
}

基本上猫鼬在引擎盖下做的是:

  1. 搜索运算符(如$set(
  2. 传递给运算符的内部值搜索其他运算符。当什么都没有找到时,mongoose会将该键解释为文档键,并将其值解释为该键的文档值

当您通过时

{
Path: {
original: "new original file!!!"
}
}

对于$set操作符,它会将其解释为:将键Path的文档值设置为这个新对象。

您应该做些什么来实现只调整original属性:

await BusinessPicture.findByIdAndUpdate(newBusinessPicture.id, { 
$set: { 
'Path.original': "new original file!!!"
} 
});

最新更新