Search code examples
node.jsbackbone.jsexpressmongoosenode-mongodb-native

MongoDB initial record does not delete


I have an app with Mongoose, Node and Backbone. I have set up a delete method to remove items from an array by "id". Everything works as it should except for the initial record - it cannot be deleted. Here is the error message when I try to delete: DELETE /test/signups/538e0e1df26a5bb086b3026a 404 Is there something funky about the initial record in MongoDB? I am new to this software. Here is my delete method:

app.delete('/test/signups/:id', isLoggedIn, function(req, res) {
    User.findOne({'_id': req.user.id }, function(err, user) {
        if (err)
            return done(err);

        if (user) {
            var found = false;
            var singlesignup = user.signup.filter(function(e){ return e._id == req.params.id })[0]

            user.signup.forEach(function (singlesignup, index) {
                if (singlesignup._id.toString() === req.params.id) {
                    found = index;  
                }

            });
            if(found) {
                user.signup.splice(found, 1);
                user.save(function(err){
                    if(!err){
                        res.send(user); 
                    }
                    else {
                        console.log(err);
                    }
                });
                res.json(200, {status: 'deleted'});
            } else {
                res.json(404, {status: 'invalid survey question deletion'});
            }
        }
    });
});

Solution

  • The problem is that you're setting found = index and then boolean evaluating found as an indication of whether it was found or not. For the case of removing the first element, found will be 0 which evaluates to false when checked with if(found) so you want to use an explicit check instead:

    if (found !== false) {
        ...