BarniPro
BarniPro

Reputation: 163

Deleted object is undefined in MEAN app

I am trying to build a MEAN stack SPA, and so far I have created the backend services using this tutorial: https://medium.com/netscape/mean-app-tutorial-with-angular-4-part-1-18691663ea96

Everything works fine when I am testing with Postman (POST, PUT, GET), however, when I try to delete an object, it results in the error:

{
 "status": 400,
 "message": "TypeError: Cannot read property 'n' of undefined"
}

Here is how my delete method looks in todos.service.js:

exports.deleteTodo = async function(id){

    try{
        var deleted = await ToDo.remove({_id: id})
        if(deleted.result.n === 0){
            throw Error("Todo Could not be deleted")
        }
        return deleted
    }catch(e){
        throw Error(e)
    }
}

and here is my todos.controller.js:

exports.removeTodo = async function(req, res, next){

    var id = req.params.id;

    try{
        var deleted = await TodoService.deleteTodo(id)
        return res.status(204).json({status:204, message: "Succesfully Todo Deleted"})
    }catch(e){
        return res.status(400).json({status: 400, message: e.message})
    }

}

When I try to delete an object, it successfully removes it (I can see it using robomongo that it has deleted it), however, I get the error message I wrote before. What could be the problem here?

Upvotes: 0

Views: 38

Answers (1)

Alex Blex
Alex Blex

Reputation: 37048

You must be using Mongoose v5. The remove method of the model doesn't require any parameters, and returns the deleted document.

In v4 remove just called collection's remove method directly, and indeed requires the condition to delete and returns number of deleted documents.

Either limit version of mongoose in your package.json to something like ^4.0.0 or use a bit more modern tutorial.

Upvotes: 1

Related Questions