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"
}
]
}
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