Mongoose delete array element in document and save

后端 未结 6 429
盖世英雄少女心
盖世英雄少女心 2020-11-28 23:53

I have an array in my model document. I would like to delete elements in that array based on a key I provide and then update MongoDB. Is this possible?

Here\'s my

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 00:53

    This is working for me and really very helpful.

    SubCategory.update({ _id: { $in:
            arrOfSubCategory.map(function (obj) {
                return mongoose.Types.ObjectId(obj);
            })
        } },
        {
            $pull: {
                coupon: couponId,
            }
        }, { multi: true }, function (err, numberAffected) {
            if(err) {
                return callback({
                    error:err
                })
            }
        })
    });
    

    I have a model which name is SubCategory and I want to remove Coupon from this category Array. I have an array of categories so I have used arrOfSubCategory. So I fetch each array of object from this array with map function with the help of $in operator.

提交回复
热议问题