1

I have already checked the following stackoverflow questions:

  1. Mongoose delete array element in document and save
  2. How to remove array element in mongodb?

Here is what I tried:

 var User = require('../model/user_model.js');

 router.put('/favoritemovies/:id', function(req, res){
     console.log(req.params.id);
     console.log(req.body.email);//I am able to console.log both value

     User.update( {_id: req.body.email}, { $pullAll: { favoriteMovies: {id:req.params.id} } } },
 });

My user model:

var mongoose = require('mongoose');

var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var userSchema =  new Schema ({
    id: ObjectId,
    name:  String,
    password: String,
    email: {type: String, unique: true},
    favoriteMovies: []
});
module.exports = mongoose.model('users', userSchema);

This is the structure of my JSON object:

{
    "_id": {
        "$oid": "583893712f599701531b60bf"
    },
    "name": "",
    "password": "",
    "email": "",
    "favoriteMovies": [
        {
            "vote_average": ,
            "video": ,
            "vote_count": ,
            "popularity": ,
            "backdrop_path": "",
            "title": "",
            "original_language": "",
            "original_title": "",
            "id": ,
            "genre_ids": [],
            "release_date": "",
            "overview": "",
            "adult": ,
            "poster_path": "",
            "_id": ""
        }

I would like to delete one or more elements from the favoriteMovies array, if their ids' matches my id. I don't get any error message, but the the element don't get removed either.

What would be the proper request to achieve that?

Community
  • 1
  • 1
GaborH
  • 689
  • 2
  • 11
  • 24

3 Answers3

2

$pullAll is used for removing multiple entries out an array, and takes an Array in its query.

You're only looking to remove one entry, so just use $pull.

{ $pull: { favoriteMovies: {id: req.params.id} } } }
Brandon Horst
  • 1,921
  • 16
  • 26
  • Thanks for your response. Unfortunately, it still doesn't work. i have checked all attributes, and it should work, but it doesn't. – GaborH Nov 25 '16 at 21:50
  • Just wanted to clarify that $pull can also be used for removing multiple entries, as long as one specifies a condition instead of a value. – John Lee Jan 02 '19 at 22:02
1

It will work using pull, you're sure that the update condition is correct ?

{_id: req.body.email}

Regarding your example :

 "_id": {
    "$oid": "583893712f599701531b60bf"
},

It seems that you should use :

{email: req.body.email}
Daphoque
  • 4,421
  • 1
  • 20
  • 31
  • I have found the solution for my problem, it is just above this post. Thanks for your input anyway. – GaborH Nov 28 '16 at 20:57
0

I found out the problem, I missed the callback function at the end of the query.

User.update( {_id: req.body.email}, { $pull: { favoriteMovies: { id: req.params.id} }
    }, function(err, model){})
GaborH
  • 689
  • 2
  • 11
  • 24