How to add reference to collection through the shell

4 views
Skip to first unread message

GuidoLx

unread,
Sep 7, 2010, 10:29:00 AM9/7/10
to mongodb-user
Hello,

I have two collections "roles" and "permissions" in my db.
I want to affect to given roles a given set of permissions.
I do not know how to append permissions to a role object I retrieved
in the shell.

I read the docs but couldn't figure out how to update my array of
permissions.

// get the role
var myrole = db.roles.find(name:"admin");
// get the permissions
var perm1 = db.permissions.find(label:"Add User");
var perm2 = db.permissions.find(label:"Delete User");
// create the references to the permissions collection
var dbRef1 = new DBRef("permissions",perm1._id);
var dbRef2 = new DBRef("permissions",perm2._id);

// this is not working
myrole.permissions.add(dbRef1);
myrole.permissions.add(dbRef2);

// this is not working
myrole.permissions[0] = dbRef1;
myrole.permissions[1] = dbRef2;

// I can do this but can't store my second reference then
myrole.permissions = dbRef1;

Thanks,
Regards,
Guido

Kristina Chodorow

unread,
Sep 7, 2010, 11:20:26 AM9/7/10
to mongod...@googlegroups.com
You have to use valid JavaScript with the shell.

// initialize your array
myrole.permissions = [];

// use "push", "add" isn't a JS array method
myrole.permissions.push(dbRef1);
myrole.permissions.push(dbRef2);

// then save it back to the db
db.roles.save(myrole);

Also, permissions seem like something that might be better to embed, not reference, although you'll have to figure out if that's true for your use case.



--
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com.
To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.


Reply all
Reply to author
Forward
0 new messages