legacybass
legacybass

Reputation: 592

Populate users having a given role in mongoose

I have two schemas that I've been using to run users and privileges on my basic site. The site consists of an express.js framework with mongoose over mongodb. The schemas look similar to this:

UserSchema = new Schema({
  Name: { type: String },
  Email: { type: String },
  Roles: [{ type: ObjectId, ref: 'Role' }]
});

RoleSchema = new Schema({
  Name: { type: String }
})

I can insert users with or without roles, and I can create roles with no problem. The issue occurs when I delete a role. The user will end up maintaining a reference to it and cause problems when trying to search on the user's roles. What I need to do is something like

UserModel.find({ })
  .where('Roles').contains(roleID)
  .exec(function(err, users) { })

This should give me only the users that have that role. Any ideas?

Upvotes: 0

Views: 1067

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146034

When a mongodb query has someArray: someValue by default it intereprets that as "match any parent document where someArray contains someValue". So this is trivial:

UserModel.find({Roles: roleId}, callback);

Side note: when you ask a question about mongoose and use the word 'populate', that means mongoose's populate feature. In this case it looks like you are asking about a vanilla collection query.

Upvotes: 1

Related Questions