Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: Remove object from array based on ID (Cast Error)

I have a model that looks like this:

mongoose.Schema({
  username: String,
  posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
});

I have an endpoint that I want to pass an ObjectID:

app.delete('/post', function(req, res) {
  User.findOne({ _id: req.user._id}, function(err, result) {
    result.pull({ _id: req.body.post_id });
  });
});

Feels like it should work, but I'm getting this error:

CastError: Cast to ObjectId failed for value "[object Object]"

What am I doing wrong?

like image 374
opticon Avatar asked Mar 13 '16 18:03

opticon


1 Answers

If you want remove one element from an array use this

User
.update( 
  {_id: req.user._id}, 
  { $pull: {posts: req.body.post_id } } 
)
.then( err => {
  ...
});

Here the documentation

like image 179
DJeanCar Avatar answered Oct 16 '22 15:10

DJeanCar