Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

62
Views
MongoDB findOneAndDelete() with multiple conditions (in nested array)

I've searched on the internet for this but haven't found a solution.

Problem : I want to delete character (one whole object in characters array).

Criteria: _id="612d0ba09403d0224b55cb6d" and id=0

I'm only able to locate account (whole presented object), but don't know how to locate the specific character in account.

User.findOneAndDelete()({ _id: "612d0ba09403d0224b55cb6d" }, (err, data) => {
            if (err) console.error('Removing character error: ', err)
            else console.log('foundChar', data)
})
{
    "_id": "612d0ba09403d0224b55cb6d",
    "nickname":"tester",
    "email":"test@test.com",
    "password":"tester",
    "characters":[ 
       {
        "id": 0,
        "name":"hdfghgfd",
        "skin":"thor",
        "exp": 0,
        "account_id":"612d0ba09403d0224b55cb6d"
       },
       {
        "id": 1,
        "name":"bdfsgfds",
        "skin":"starlord",
        "exp": 0,
        "account_id":"612d0ba09403d0224b55cb6d"
       }
    ]
}
5 months ago · Juan Pablo Isaza
1 answers
Answer question

0

To removing a element from an array you have to use update and $pull

From the docs:

The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

So you need this query:

yourCollection.updateOne({
  _id: "612d0ba09403d0224b55cb6d"
},
{
  "$pull": {
    "characters": {
      "id": 0
    }
  }
})

Example here

5 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.