schema: -> a string array based on an enum

2,725 views
Skip to first unread message

Thibault

unread,
Jul 6, 2011, 4:26:56 AM7/6/11
to Mongoose Node.JS ORM
Hi,

I would like to know if it is possible to define something like that:

var User = new Schema({
...
roles: [{ type: String, enum: ['admin', 'creator', 'contact'] }]
...
});

because when I try to insert document with an array of role ( ...
'roles':['creator'] ... ) I've got this exception: uncaught:
CastError: Cast to undefined failed for value "undefined"

However to solve it I create another schema:

var Role = new Schema({
name: { type: String, enum: ['admin', 'creator', 'contact'] }
});

And change the user schema like that:
var User = new Schema({
...
roles: [Role]
...
});

So, when I insert data I have to do like that ... 'roles':
[{'name':'creator'}] ... I's working but I found it no very smart.

Hace you got another solution?

thx

dale tan

unread,
Jul 6, 2011, 9:41:26 AM7/6/11
to mongoo...@googlegroups.com
defining the "roles" as type String with an enum seems to be a good way to cast that value.  You can also add a "default" property as one of the enum values if you'd like.  You can see this in action here: http://nodetuts.com/tutorials/21-nodejs-mongodb-and-mongoose-11.html#video

dale
--
-- 
CONFIDENTIALITY NOTICE: This e-mail transmission, and any documents, files or previous e-mail messages attached to it may contain confidential
information that is legally privileged and is intended for the designated
recipient only. If you have received it in error, please notify the sender
immediately and delete the original. Any other use of the email by you is
STRICTLY PROHIBITED.

Thibault

unread,
Jul 7, 2011, 3:22:44 AM7/7/11
to Mongoose Node.JS ORM
Hi,
Thx for the response, finaly found a solution:

// i define roles as an array
var User = new Schema({
...
roles: [String]
...

});

// and validate the values match the content of the enum:
User.path('roles').validate(function(roles) {
var refs = ['creator', 'admin', 'contact'];
roles.forEach(function(role){
var valid = false;
refs.forEach(function(ref){
if(ref == role) {
valid = true;
return;
}
});
if(!valid) return false;
});
return roles.length > 0;
}, 'roles not valid');


On Jul 6, 3:41 pm, dale tan <wtd...@gmail.com> wrote:
> defining the "roles" as type String with an enum seems to be a good way to
> cast that value.  You can also add a "default" property as one of the enum
> values if you'd like.  You can see this in action here:http://nodetuts.com/tutorials/21-nodejs-mongodb-and-mongoose-11.html#...
Reply all
Reply to author
Forward
0 new messages