4

I have this document in my collection:

{
    "_id" : ObjectId("52718433e18a711923000005"),
    "owners" : [
        ObjectId("52718433e18a711923000004"),
        ObjectId("52ed40dccc5bc50000000003"),
        ObjectId("52ed4171abe2780000000003")
    ]
}

I have the following statement, where I am trying to remove one of the values in owners field:

Business.update({_id:req.body._id}, {$pull:{"owners":req.body.userid}}, function(err){
    if(err){
        res.json(500, {message:"Could not remove user from admin list"});
    }else{
        res.json(200);
    }
});

I know that req.body._id and req.body.userid have valid values:

{ _id: '52718433e18a711923000005',
  userid: '52ed4171abe2780000000003' }

Other operations, such as finding business by ID, etc, work, so it's not an ObjectId format issue. What else could it be?

-- Edit: here is my (abbreviated) schema definition:

var BusinessSchema = new Schema({
    business_name: {type: String, required: true},
    owners: {type: Array}
});
2
  • 1
    Can you update your question to include your schema definition? Commented Feb 4, 2014 at 21:27
  • I added it to the question. Commented Feb 4, 2014 at 21:32

2 Answers 2

3

Your current schema doesn't provide any direction to Mongoose regarding the data type contained within the owners array field. If you want Mongoose to cast your string to an ObjectID you need to provide type information in your schema:

var BusinessSchema = new Schema({
    business_name: {type: String, required: true},
    owners: [{type: Schema.ObjectId}]
});
Sign up to request clarification or add additional context in comments.

Comments

2

It looks like a conversion to ObjectId is required when trying to match values to pull. But not to search. So this works:

var ObjectId = require('mongoose').Types.ObjectId;

Business.update({_id:req.body._id}, {$pull:{"owners": new ObjectId(req.body.userid)}}, function(err){
    if(err){
        res.json(500, {message:"Could not remove user from admin list"});
    }else{
        res.json(200);
    }
});

-- Edit: So, if I change my schema from owners: {type: Array} to owners: [Schema.Types.ObjectId], I can skip the conversion, and my original statement works.

1 Comment

The casting of the String to a ObjectId is required to me with [{ type: Schema.Types.ObjectId, ref: 'owner' }]. Was there a change in MongoDB / Mongoose since '14? Could it also be that refis interfering with the cast?

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.