Home > Net >  How to use $pull to delete a particular data from a document in mongoDB
How to use $pull to delete a particular data from a document in mongoDB

Time:01-27

I'm pretty new in MongoDB,I want to delete a particular object from an array of objects in a document. I tried a lot and finds a lot of questions in StackOverflow.But none of them worked (maybe it's my fault)

following is a document from a collection that is matched by the user with userId

61f15af01a3c53dfa87e38e6

The Document

{
        "_id": "61f15af01a3c53dfa87e38ed",
        "user": "61f15af01a3c53dfa87e38e6",
        "transactions": [
            {
                "amount": 50,
                "category": "Bills",
                "type": "Expense",
                "_id": "61f15af01a3c53dfa87e38ee"
            },
            {
                "amount": 100,
                "category": "Lottery",
                "type": "Income",
                "_id": "61f15af01a3c53dfa87e38ef"
            },
            {
                "amount": 200,
                "category": "Salary",
                "type": "Income",
                "_id": "61f15af01a3c53dfa87e38f0"
            },
        ]
    }

I want to delete the transaction with an Id of 61f15af01a3c53dfa87e38ef

I tried the below one (I don't know whether it is correct)

 const  allTransactions = await Transactions.findOne({ user: req.user._id });
 const updatedTransactions = await allTransactions.update(
      {  },
      { $pull: { transactions: { id: req.params.id } } },
    );

Can anyone Spot the mistake and how can I achieve it ?

Thanks in advance :)

CodePudding user response:

You can do it in one database call using below statement:

await Transactions.update(
    { user: "61f15af01a3c53dfa87e38e6" }, 
    { $pull: { "transactions": { _id: "61f15af01a3c53dfa87e38f0" } } } 
)

Mongo Playground

Also make sure types match. If _id is of type ObjectId instead of string you should convert req.params.id to ObjectId first. See below:

await Transactions.update(
    { user: mongoose.Types.ObjectId(req.user._id) }, 
    { $pull: { "transactions": { _id: mongoose.Types.ObjectId(req.params.id) } } } 
)
  •  Tags:  
  • Related