9

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?

opticon
  • 3,494
  • 5
  • 37
  • 61

3 Answers3

10

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

DJeanCar
  • 1,463
  • 1
  • 11
  • 13
0
This is because when you are running user findOne query it returns an object to you.(the findOne function returns only one object)

User.findOne({ _id: req.user._id}, function(err, result) {

 /// result is an object
    result.pull({ _id: req.body.post_id });
  });

and what is result.pull you are trying to pull an element from object this is the wrong way to do

do like this 
delete result._id;


and if you want more elements from user query in from of array you can use 
User.find({ _id: req.user._id}, function(err, result) {

// result.slice for slice you can see this http://stackoverflow.com/questions/3396088/how-do-i-remove-an-object-from-an-array-with-javascript
  });

then you can do slice on array of object
Tal Avissar
  • 10,088
  • 6
  • 45
  • 70
Himanshu sharma
  • 7,487
  • 4
  • 42
  • 75
-1

In order to make a research with an id in a collection you need to create a new ObjectId and then pass the id into it.

app.delete('/post', function(req, res) {
    User.findOne({ _id: _id: ObjectId (req.user._id)}, function(err, result) {
        result.pull({ _id: ObjectId (req.body.post_id) });
    });
 });
PazzoTotale
  • 411
  • 2
  • 5
  • 14