问题描述
我刚刚从 5.11 升级到 Mongoose 5.12,并且正在使用 Typescript。我有这个架构
const MyFileSchema = new Schema<IMyFile>({
objectID: { type: String,required: true },attachments: { type: Array,required: false }
},{ collection: 'my_file' });
现在这个 findOneAndUpdate 突然无法编译...
await MyFile.findOneAndUpdate(
{ objectID },{
$push: {
attachments: { fileName: fileName,id: fileID },},);
抱怨...
Type '{ attachments: { fileName: string; id: string; }; }' is not assignable to type 'PushOperator<_AllowStringsForIds<LeanDocument<any>>>'.
Type '{ attachments: { fileName: string; id: string; }; }' is not assignable to type 'NotAcceptedFields<_AllowStringsForIds<LeanDocument<any>>,readonly any[]>'.
Property 'attachments' is incompatible with index signature.
Type '{ fileName: string; id: string; }' is not assignable to type 'undefined'.
是否有另一种编写上述内容的方法来避免我使用 Mongoose 5.11 时未发生的编译错误?
解决方法
await MyFile.findOneAndUpdate(
objectID,{
$push: {
attachments: { fileName: fileName,id: fileID },},);
试试这个它会起作用。
注意:您需要从 objectID 搜索参数中删除 {}
括号。