tiny tin tiny tin - 1 month ago 6
Node.js Question

Why $pull operator doesn't work on MongoDB

{
"_id" : ObjectId("581472c3c65f3a1b3412f147"),
"name" : "这是一级目录-----1",
"englishName" : "zzzzz",
"stage" : "first",
"children" : [
ObjectId("581472f1c65f3a1b3412f149"),
ObjectId("581472f4c65f3a1b3412f14a")
],
"type" : "group",
"order" : 50,
"__v" : 0
}


I want to remove children[1] by
$pull
, but it doesn't work.

var _id = req.fields._id; //581472f4c65f3a1b3412f14a
var parent_id = req.fields.parent; //581472c3c65f3a1b3412f147
db.Group.update({ _id: parent_id }, { $pull:{children:_id} },function(err,result){
console.log(result);
cb(err,result);
})


I have try to use
{$pull:{children:ObjectId(_id)}}
instead of
{ $pull:{children:_id} }
,but still failed.

Mongoose Schema

var groupSchema=new Schema({
name:String,
englishName:String,
order:{
type:Number,
default:50
},
type:{
type:String,
default:"group"
},
stage:String,
children:{
type:Array,
default:[]
}
});


My English is very poor. Please forgive me.

Answer

The folowing request works fine :

db.Group.update({
   _id: ObjectId("581472c3c65f3a1b3412f147")
},
{
   $pull:{
      children: ObjectId("581472f4c65f3a1b3412f14a")
   }
})

so make sure that your var _id and parent_id are ObjectId, and not String.

you can create objectId like this:

var object = new ObjectId("581472c3c65f3a1b3412f147")