findByIdAndRemove在Mongoose中不能同时删除多个文档



我试图同时删除多个文档,这个想法被发送到findByIdAndRemove方法几个_ids,这个问题看起来像是转换中的问题,但我不知道如何解决它。

我在谷歌上搜索了一下,但目前我没有找到任何可以帮助我理解自己做错了什么的东西。我得到这个错误:

(node:95729) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{
_id: {
'$in': [
'5f118f0c7bec9a497dfafbf0',
'5f118fd93d847749e3ecffe3',
'5f11902ff143154a16d8c940',
'5f119061a407ef4a26a5b3bc'
]
},
user: { '$eq': '5efeaf2f3ded3b581c4ba695' }
}" at path "_id" for model "Notification"
at new CastError (/Users/papixulo/server/massages_backend/node_modules/mongoose/lib/error/cast.js:29:11)

这是代码:

const ids = req.body.ids;
var object_ids_array: string[] = [];

ids.forEach(id => {
return object_ids_array.push((id));
});


console.log('******ids_array',  object_ids_array);

// var id = new ObjectId(request.params.Id);
// Booking.findOne({packages: {$in: packages_ids}}).select('_id _package _date').exec()

await Notification.findByIdAndRemove({ _id: {$in: object_ids_array}, 'user': {$eq: req.user._id}}, (err: any, docs: any) => {
console.log('docs', docs);
console.log('err', err);

if ( err || !docs) {
validations.push({code: 150, message: 'error_removing_notification'});
}
if( validations.length > 0 ) {
return res.status(400).json( {
code: 400,
error: validations
});    
}
return res.status(200).json({
code: 200,
success: true
});
}); 

以防万一,这就是模型:

const notificationSchema = new Schema ( {

title: {
type: String
},
notification_type: {
type: String
},
text: {
type: String
},
isRead: {
type: Boolean
},
date: {
type: Number // When the notification will be triggered?
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: [ true, 'A reference to a user must exist']
},
});

最后我用deleteMany((解决了它https://mongoosejs.com/docs/api.html#model_Model.deleteMany

最新更新