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

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

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': }, {
            $pull: {
                "logs": { "_id": }
        }, { safe: true, multi: true },
        function(err, foundAnimal) {
            if (err) {
            else {
                res.redirect("/animals/" + foundAnimal._id + "/logs");

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



answered 6 months ago David Vicente #1

I think the problem is 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 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:


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


Hope it helps

comments powered by Disqus