1

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.

2
  • Do you call save() after pull()? Commented May 24, 2014 at 17:37
  • Yes I do. Same as I did for Push. Commented May 25, 2014 at 5:29

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.