mongodb - How would I develop a relationship User belongs to Groups in Mongoose & Node.js? -


i trying teach myself node.js, coming rails, , want establish relationship:

  • a group has_many users, user belongs_to group

how go doing in models?

//for user var mongoose = require('mongoose'); var schema = mongoose.schema;  var userschema = new schema({     name: string });  module.exports = mongoose.model('user', userschema);  //for group var mongoose = require('mongoose'); var schema = mongoose.schema;  var groupschema = new schema({     name: string });  module.exports = mongoose.model('group', groupschema); 

also allow moderator kick out of group if person obnoxious. how target user belonging group , delete user. seems more complicated traditional crud methods. need nested resources in rails, or equivalent?

mongoose has feature called population can use set "relationships" (mongodb has limited support relationships).

your schema this:

var userschema = new schema({   name : string,   group: { type: schema.types.objectid, ref: 'group' } });  var groupschema = new schema({   name  : string,   users : [ { type: schema.types.objectid, ref: 'user' } ] }); 

in other words: user model has group property points group user belongs to, , group model has users property (an array) contains references users belong group.

to associate user group (assuming group variable group instance):

user.group = group; user.save(...); 

and add user group:

group.users.push(user); group.save(...); 

however, should aware array properties in mongodb documents have limited scalability. think few dozen items in array work fine, when number of users in group expected in thousands, won't viable solution. in situation, should consider "junction collection" (similar sql's "junction table").

to remove user particular group, think need use .update():

group.update({ _id: group._id }, { $pull : { users : user._id }}) 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -