GaborH GaborH - 5 days ago 5
JSON Question

How to delete an element of an array in a JSON Object with Mongoose?

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?

Answer

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){})
Comments