Question

I have a collection called 'users' where a typical user entry looks something like this:

{
"__v" : 0,
"_id" : ObjectId("536d1ac80bdc7e680f3436c0"),
"joinDate" : ISODate("2014-05-09T18:13:28.079Z"),
"lastActiveDate" : ISODate("2014-05-09T18:13:48.918Z"),
"lastSocketId" : null,
"password" : "Johndoe6",
"roles" : ['mod'], // I want this to be checked
"username" : "johndoe6"
}

I want to create an if function that finds a user variable targetuser, and checks to see if his 'roles' array contains a 'mod'. How can this be done with mongoose?

Was it helpful?

Solution

It can be done easily. Code below describes in detail what must be done to achieve this.

Steps:

  1. get mongoose module
  2. connect to mongo and find the right database
  3. make a schema of your collection (in this case only users)
  4. add a custom method that returns true if the role 'mod' exists in the array. Note: mongo collection doesn't have structure, so it might be good to run a check if the property 'roles' exists and it is an array.
  5. model the created schema.
  6. test it by finding random (one) document/user and check if it is a moderator.

So, this is programmed as:

//  get mongoose.
var mongoose = require('mongoose');

//  connect to your local pc on database myDB.
mongoose.connect('mongodb://localhost:27017/myDB');

//  your userschema.
var schema = new mongoose.Schema({
  joinDate      : {type:Date, default:Date.now},
  lastActiveDate: Date,
  lastSocketId  : String,
  username      : String,
  password      : String,
  roles         : Array
});

//  attach custom method.
schema.methods.isModerator = function() {
  //  if array roles has text 'mod' then it's true.
  return (this.roles.indexOf('mod')>-1);
};

//  model that schema giving the name 'users'.
var model = mongoose.model('users', schema);

//  find any user.
model.findOne({}, function(err, user)
{
  //  if there are no errors and we found an user.
  // log that result.
  if (!err && user) console.log(user.isModerator());
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top