How to set ObjectId to null or remove ObjectId

804 views
Skip to first unread message

Rob Hicks

unread,
Aug 28, 2013, 11:55:14 AM8/28/13
to mongoo...@googlegroups.com

I have a schema that includes a field that is set to ObjectId. The field is set to the id of the document's parent. The document is not embedded in the parent. And, the field is not required.

I want to remove the parent in some cases so the document is at the root of hierarchy. Unfortunately, doing so results in a "Cast toObjectId failed ..." error.

What is the proper way to set the ObjectId to null or to remove the ObjectId?

I have tried to set the parent to undefined.

schema.method('removeParent', function(parentId, cb){
        var self = this;
        var err = null;
        if(parentId){
            self.parent = undefined;
            self.path = self.path.replace(parentId + pathSeparator, '');
        } else {
            err = 'parent ID required';
        }
        return cb(err, self);
    });




Jason Crawford

unread,
Aug 28, 2013, 12:02:49 PM8/28/13
to mongoo...@googlegroups.com
In my app I am able to set an ObjectId property to undefined and save it, no problem. Maybe it has something to do with your schema?

-Jason


--
Documentation - http://mongoosejs.com/
Plugins - http://plugins.mongoosejs.com/
Bug Reports - http://github.com/learnboost/mongoose
Production Examples - http://mongoosejs.tumblr.com/
StackOverflow - http://stackoverflow.com/questions/tagged/mongoose
Google Groups - https://groups.google.com/forum/?fromgroups#!forum/mongoose-orm
Twitter - https://twitter.com/mongoosejs
IRC - #mongoosejs
---
You received this message because you are subscribed to the Google Groups "Mongoose Node.JS ODM" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoose-orm...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Stefano Pongelli

unread,
Aug 28, 2013, 1:14:23 PM8/28/13
to Rob Hicks, mongoo...@googlegroups.com
Not sure if it helps but I noticed that setting ObjectId to undefined and then saving works, while trying something like: model.update({ _id: id }, { prop: undefined }, cb)  
fails.


Cheers
Stefano
Reply all
Reply to author
Forward
0 new messages