cfibla cfibla - 1 month ago 7
Node.js Question

How can I delete an item from an Object in NodeJs/express/mongoose?

I know this has been asked before, but no one of the answers worked for me.
In my App, I have a users collection in MongoDb. These users collection have an array field named 'segActuacions' that can be modified within a form. This form sends this Object to router:

{"segActuacions.0.date":"27/09/2016",
"segActuacions.0.body":"first item",
"segActuacions.1.date":"27/09/2016",
"segActuacions.1.body":"second item"}


router has this line to go to controller:

router.delete('/seg_act_upd_EE/:id/actDel/:i',
sessionController.loginRequired,
userController.actuaDelete);


where ':id' is User-id, and ':i' is the index of segActuacions

controller has this code:

exports.actuaDelete = function (req, res) {

var userId = req.params.id;
var userI = req.params.i;
var usr = req.body;


delete usr['segActuacions.userI.date'];
delete usr['segActuacions.userI.body'];

models.User.findByIdAndUpdate(userId, usr,

function (error, user){
if (error) res.json(error);
res.redirect('/list_EE');
});
}


I want to delete the fields 'i' of the Object (for instance: if i=0, i'd like to delete "segActuacions.0.date" and "segActuacions.0.body", ...but nothing happens

Thanks for your answer

Answer

Note your delete wouldn't work because you are using userI as a string and not using the variable value. Also update will just update the fields that are in the object.

But I think you should use $unset, like the following:

var updateObj = {};
updateObj['segActuacions'] = {};
updateObj['segActuacions'][userI] = {};
updateObj['segActuacions'][userI]['body'] = '';
updateObj['segActuacions'][userI]['date'] = '';

var update = { $unset:  updateObj };

models.User.findByIdAndUpdate(userId, update, function (error, user){
    if (error) res.json(error);
    res.redirect('/list_EE');
});

(This code can be improved and wasn't tested)

Comments