I am using the following code snippet below to delete an array item that is within an object which is itself an array item in a document.
const query = {
userId: context.user.id
}
const userProfile = await usersCollection.findOne(query, {
payment: 1
})
const payment = userProfile.payment || {}
const activePaymentGateways = payment.activePaymentGateways
// get active gateways
const activeGateways = payment.gateways.filter(gateway => activePaymentGateways.includes(gateway.name))
// get gateway user wants to delete card from
const pg = activeGateways.find(gateway => gateway.name === gatewayName)
const defaultCardId = pg.defaultCardId
let update = {}
if (paymentCardId === defaultCardId) {
// delete default card
update = {
$pull: {
"payment.gateways.$[gateway].cards": {
id: paymentCardId
}
},
$set: {
"payment.gateways.$[gateway].defaultCardId": ""
}
}
} else {
// delete non-default card
update = {
$pull: {
"payment.gateways.$[gateway].cards": {
id: paymentCardId
}
}
}
}
const options = {
returnDocument: "after",
returnNewDocument: true,
projection: {
"payment.gateways": 1
},
arrayFilters: [{ "gateway.name": gatewayName }]
}
const result = await usersCollection.findOneAndUpdate(
query,
update,
options
)
let response
...
When run in atlas, I get “FunctionError: No array filter found for identifier ‘gateway’ in path ‘payment.gateways.$[gateway].cards’” but can’t replicate this error in my local setup where I use jest-mongodb (which uses mongodb memory server) for testing.
Do you have any idea on what I’m doing wrong?
Thanks