Я хочу удалить записи на основе входящего (со стороны клиента) array
_ids
. Моя функция удаления выглядит следующим образом
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
});
}
});
});
}
Но я получаю ошибку, как это
message: "Cast to ObjectId failed for value "{ _id: { '$in': [ 5e1f2e54d4252144ec17501a ] } }" at
path "_id" for model "referralLinks""
name: "CastError"
stringValue: ""{ _id: { '$in': [ 5e1f2e54d4252144ec17501a ] } }""
kind: "ObjectId"
Как я могу решить это?
Всего 1 ответ
Так что в общем случае mongoose findById*'s
принимает один _id
качестве фильтра, если вы передаете строку, внутренне mongoose преобразует строку в _id
, поэтому вы не можете передать ей массив - если вы хотите работать с findByIdAndRemove
- вам нужно выполнить цикл _id
и сделать несколько вызовов БД (удаляя каждый документ), также я немного изменил ваш код, зачем проверять !err
? скорее, вы можете проверить, if(err)
сначала, затем проверить, чтобы записать результат. Попробуй это :
Попробуй это :
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
});
}
});
});
}