Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose - remove element in array using $pull

I have a node object that looks like this:

{
   "_id":"58b336e105ac8eec70aef159",
   "name":"my node",
   "ip":"192.168.1.1",
   "__v":0,
   "configuration":{
       "links":[
         {
            "linkName":"athena_fw_listen_tcp_5555",
            "_id":"58b336e105ac8eec70aef15d",
            "local":true
         },
         {
            "linkName":"athena_fw_listen_udp_5554",
            "_id":"58b336e105ac8eec70aef15c",
            "local":true
         }
      ]
   }
}

I am sending a delete request to my express server that looks like this: DELETE http://localhost:9000/api/nodes/58b336e105ac8eec70aef159/links/58b336e105ac8eec70aef15d

I followed instructions in $pull mongodb documentation and I also tried this

But it does not seem to work, as I keep receiving: 500 (Internal Server Error)

This is how the code on my express side looks like:

exports.destroyLink = function(req, res) {
    Node.findById(req.params.id, function(err, node) {
        if (err) { return handleError(res, err); }
        if (!node) { return res.status(404).send('Not Found'); }
        console.log("Node", JSON.stringify(node))
        console.log("Params", req.params)

        node
            .update({ '_id': req.params.id }, { $pull: { 'configuration': { 'links': { '_id': req.params.linkId } } } }, false, true)
            .then(err => {
                if (err) { return handleError(res, err); }
                return res.status(204).send('No Content');
            });
    })
};

The express router contains this: router.delete('/:id/links/:linkId', controller.destroyLink);

So I am expecting id and linkId as params, I use id (_id: req.params.id) to target a specific node and linkId (_id: req.params.linkId) to target a specific link, but it doesn't work!

Need help resolving the issue, I don't know what I am missing here!

like image 761
elmiomar Avatar asked Feb 26 '17 20:02

elmiomar


1 Answers

Hi all and thank you for your help. I finally got it to work!!!

After almost 3 hours of troubleshooting :'( :'( this is the solution that used:

exports.destroyLink = function(req, res) {
Node.findByIdAndUpdate(
    req.params.id, { $pull: { "configuration.links": { _id: req.params.linkId } } }, { safe: true, upsert: true },
    function(err, node) {
        if (err) { return handleError(res, err); }
        return res.status(200).json(node.configuration.links);
    });
};

Instead of findById then update the node, I did both using findByIdAndUpdate. It' working perfectly now!!!

I still don't find an explanation for the other version though. But anyways glad it's working this way.

like image 184
elmiomar Avatar answered Oct 03 '22 04:10

elmiomar