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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...