I want to delete records based on incoming(from client side) array
of _ids
. My delete function is like this
export function removeReferral(ids) {
return new Promise((resolve, reject) => {
ReferralLink.findByIdAndRemove({ _id: { $in: (ids).map(mongoose.Types.ObjectId) } }, (err, link) => {
console.log('delete referrals response : ', link)
if (!err) {
resolve({
success: true,
message: "Referral removed successfully",
data: null
});
} else {
resolve({
success: false,
message: "Unable to remove referral",
data: err
});
}
});
});
}
But i am getting error like this
message: "Cast to ObjectId failed for value "{ _id: { '$in': [ 5e1f2e54d4252144ec17501a ] } }" at
path "_id" for model "referralLinks""
name: "CastError"
stringValue: ""{ _id: { '$in': [ 5e1f2e54d4252144ec17501a ] } }""
kind: "ObjectId"
How can i resolve it?
So in general mongoose findById*'s
would accept a single _id
as filter, if you pass a string internally mongoose converts string to _id
, So you cannot pass in an array to it - if want to work with findByIdAndRemove
- you need to loop on _id
's and make multiple DB calls (deleting each document), Also I've changed your code a bit, why to check !err
? rather you can check if(err)
at first then a check to write result. Try this :
Try this :
export function removeReferral(ids) {
return new Promise((resolve, reject) => {
ReferralLink.deleteMany({ _id: { $in: (ids).map(mongoose.Types.ObjectId) } }, (err, link) => {
console.log('delete referrals response : ', link)
if (err) {
resolve({
success: false,
message: "Unable to remove referral",
data: err
});
} else if (link.n > 0) { /** Checking if atleast one _id in input array is removed,
Or if you need to check all are deleted then n == array.length */
resolve({
success: true,
message: "Referral removed successfully",
data: null
});
} else {
resolve({
success: true,
message: "Not able to remove Referrals successfully",
data: null
});
}
});
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.