Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

63
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos