madu
madu

Reputation: 5460

MongoDB: Removing an array object in Mongoose

I have the following Schema:

var userSchema = mongoose.Schema({

    local            : {
        email        : String,
        password     : String,
        movies       : [{
                          moviename   : String,
                          rating      : Number
                        }],
    }

});

And I use the following way to add entries to the array:

user.local.movies.push({ moviename  : "Top Gun", rating     : 80});
user.save(function (err) {
                if (err)
                    console.log("Error in saving");

                res.end(0);
            });

But I need to remove entries too. I need to be able to remove entries by the "moviename" name. I tried using pull:

 user.local.movies.pull({ moviename  : "Top Gun"});

but it did not work.

Could someone please let me know how I can remove entries from the array?

Thank you.

Upvotes: 1

Views: 396

Answers (2)

dylants
dylants

Reputation: 23410

One way of doing this is to use the splice function to remove the element from the array, assuming you can find the index. So for instance:

User.findOne(function(err, user) {
    var movies, index;

    movies = user.movies;

    for (index = 0; index < movies.length; index++) {
        if (movies[index].moviename === "Top Gun") {
            break;
        }
    }
    if (index !== movies.length) {
        movies.splice(index, 1);
    }

    user.save(function(err, user) {
        res.send(user);
    });

});

(Know that the above code does this for only one user, and hard codes the movie name to remove, but you get the idea.)

Upvotes: 2

JohnnyHK
JohnnyHK

Reputation: 312129

I think it's easier to use an explicit update call instead of Mongoose's array manipulation methods which don't always work as you'd expect:

User.update({_id: user._id}, 
    {$pull: {'local.movies': {moviename: 'Top Gun'}}}, callback);

Upvotes: 2

Related Questions