I need to delete a location object from the locations array. It is deeply nested. I followed mongoose documentation but my attempts didn't work:
lists = [{ "listName": "Test", "_id": "8d55f0afe545a0178c320706", "listId": "5fd9a3bef6c39b2f9c4df65b", "date": "12/15/2020", "dueDate": "2020-11-18", "items": [ { "itemNumber": 123, "description": "item123", "onHand": 60, "_id": "13dd1f26ecd2baeb61b3b455", "locations": [ { "locationName": "loc1", "count": 10, "_id": "50a2c969465ba8010bd48977" }, { "locationName": "loc2", "count": 20, "_id": "51c2f1d25311dc8fabdbf604a59b" }, { "locationName": "Loc3", "count": 30, "_id": "7cb0c1f51a91c384846d65f8b2ae" } ] }, {more lists}
Attempt:
router.post("/lists/deleteLoc", (req, res) => { const { listId, list_id, item_id, location_id } = req.body; List.updateOne({ "lists.listId": listId, "lists._id": list_id }, { $pull: { "lists.$.items": { locations: { $elemMatch: { _id: location_id }).then(() => res.json({ msg: "location removed" })).catch((err) => res.status(400).json({ msg: "Error: " + err })); });
If the request location_id was "7cb0c1f51a91c384846d65f8b2ae" it should delete the last location from the array. The desired result:
lists = [{ "listName": "Test", "_id": "8d55f0afe545a0178c320706", "listId": "5fd9a3bef6c39b2f9c4df65b", "date": "12/15/2020", "dueDate": "2020-11-18", "items": [ { "itemNumber": 123, "description": "item123", "onHand": 60, "_id": "13dd1f26ecd2baeb61b3b455", "locations": [ { "locationName": "loc1", "count": 10, "_id": "50a2c969465ba8010bd48977" }, { "locationName": "loc2", "count": 20, "_id": "51c2f1d25311dc8fabdbf604a59b" } ] }, {more lists}
I've tried basically all variations of this, but none have worked.
I'm also not sure if making a router.post or an axios.post request for deletion is correct. Should this be axios.delete and router.delete?
I've tried this in one of my similar DB and worked!
List.updateOne({ "listId": yourListId },
{
'$pull': {
'items.$[item].locations': { "_id": yourLocationId }
}
}, {
"arrayFilters": [
{
"item._id": yourItemId
}
]
}, function (err) {
if (err) {
res.json(err)
} else {
res.json({ message: "Updated" })
}
})
}
You've to put the values that're inside your DB from the object that you want to delete.
So if you want to delete the object with
"locationname": "Loc3"
You should use
var yourListId = "5fd9a3bef6c39b2f9c4df65b";
var yourItemId = "13dd1f26ecd2baeb61b3b455";
var yourLocationId = "7cb0c1f51a91c384846d65f8b2ae";
Try it out!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.