Im trying to delete multiple objectIds from an array within a document.
This is what it looks like at the moment:
const foundTransactions=await Transaction.find({parentPortfolio:portfolioId,parentAccount:accountName})
var idArray =[]
foundTransactions.map((element)=>{
idArray.push(element._id)
})
const deletedAccount=await Portfolio.updateOne({_id:portfolioId},
{$pull:{accounts:{name:accountName},transactions:{$in:[idArray]}}},{multi:true})
I am looking through the Transactions collection and logging all that are soon to be deleted (this is because there is no way to log Id of documents as they are being deleted by deleteMany). Once I insert all the _ids inside an array, I pass this array through the $in operator as the search query for the pull operator. This pull will delete the account with the given name, but will not delete any transactions within the Portfolio collection.
Portfolio modal for reference:
const portfolioSchema = new Schema({
name:{
type: String,
required:true,
default:"My Portfolio",
validate:[(val)=>{return val.length<=30},"{PATH} is too long. 30 characters max."]
}
accounts:[Account],//subdocument
transactions:{//array of Object ids.
type:[{
type:Schema.Types.ObjectId,
ref:"Transaction"
}],
validate:[arrayLimit,"{PATH} exceeds the limit of 50"]
}
})
I am well aware why the account delete works and how I should be doing the pull/in combo to delete all ObjectIds within an document, but I have no idea why my implementation doesn't work.
I have tried:
- Not using $in operator and passing parentAccount:accountName
- using $ operator to find array index (not useful if deleting multiple indexes)
- changing objectid toString()
- removing and adding multi:true
- removing $in operator and leaving just the array inside the object field
- adding quotes on everything (parameters within fields)
- replacing pull with pullAll
I appreciate any and all help