How to delete an item in an array using Mongoose/Node.js

CSE Source

So I've read and tried to implement the other solutions for this. I'm just trying to get some insight into why it's not working for me. This is my first project with back end work. I'm working my way through a course but wanted to try something on my own to make the concepts stick.

Here is my Schema

//ANIMAL
var animalSchema = new mongoose.Schema({
    image: String,
    name: String,
    variety: String,
    DOB: Date,
    logs: [{
        amount: Number,
        notes: String,
        dateMilked: Date
    }],
    created: { type: Date, default: Date.now }
});

So far I've managed to get all of my RESTful routes for animals and logs working except to delete a log.

This is what I have, but it isn't deleting anything - it also doesn't throw any errors.

app.delete("/animals/:id/logs/:id", function(req, res) {
    Animal.findOneAndUpdate({ 'logs._id': req.params.id }, {
            $pull: {
                "logs": { "_id": req.body.id }
            }
        }, { safe: true, multi: true },
        function(err, foundAnimal) {
            if (err) {
                console.log(err);
                res.redirect("/");
            }
            else {
                res.redirect("/animals/" + foundAnimal._id + "/logs");
            }
        });
});

Any help or insight would be great!! I'm looking to learn!

javascriptnode.jsmongodbexpressmongoose

Answers

answered 6 months ago David Vicente #1

I think the problem is req.body.id probably doesn't have any value, because you are sending both ids in the path. And if you call them the same app.delete("/animals/:id/logs/:id", I'm pretty sure req.params.id is going to have one of two values, but you are not going to be able to get the other one.

You should call them with different names, like this:

app.delete("/animals/:animalId/logs/:logId",

and then you can access to both variables without any collision:

req.params.animalId
req.params.logId

Hope it helps

comments powered by Disqus