SlashTag SlashTag - 3 months ago 10
Node.js Question

Remove a document nested in an array via mongoose

I'm trying to remove a document that is nested inside of an array which is nested inside of a document in MongoDB.

Schema

{
"_id": 12345,
"id": 12345,
"name": "Test",
"links": [],
"training": [],
"about": [
{
"contents": "Test Contents 0",
"heading": "Test Heading 0"
},
{
"contents": "Test Contents 1",
"heading": "Test Heading 1"
},
{
"contents": "Test Contents 2",
"heading": "Test Heading 2"
}
]
}


I want to remove the sub doc that matches the route

'/:_id/:section/:item'


Such that if I send a
DELETE
to
/12345/about/1
, the sub doc containing "Test Heading 1" will be removed entirely.

I've tried many different methods such as

.delete(function (req, res) {
var section = req.params.section_name;
var item = req.params.item;

Tool.findOne({'id': req.params._id}, function (err, tool) {
tool.set(section[item], null);
tool.save(function (err) {
res.send(err);
})
});
});


But none seem to work.

Any help would be greatly appreciated.

Answer

This should work perfectly

.delete(function (req, res) {
    var section = req.params.section_name;
    //convert string to int
    var item = +req.params.item; //or use parseInt(req.params.item)

    Tool.findOne({'id': req.params._id}, function (err, tool) {
        tool[section].splice(item, 1);
        tool.save(function (err) {
            res.send(err);
        })
    });
});

It's converted to

tool[section].splice(item, 1);
tool.about.splice(1, 1); //remove 1 item from given index

About splice

array.splice(index, 1);

The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.

Comments