I am trying to add an instance method to my MessageBoard model to tell me whether a given User is a member of that MessageBoard.
The MessageBoard schema contains
members: [{
type: Schema.Types.ObjectId
ref: 'User'
}]
But my instance method...
MessageBoardSchema.methods.isUserMember = function(user) {
return (this.members.id(user));
};
...tells me that the method id
does not exist on the object this.members.
I haven't been able to find a solution in other similar questions because I am using a reference rather than a nested Schema here.
id
method works for embedded documents where you have real documents within you members array; what you have in this.members
is an array of ObjecIds. I would recommend you to use underscore.js
If user is indeed a user_id:
MessageBoardSchema.methods.isUserMember = function(user) {
var user_found = _.any(this.members, function(member){
// Use toString() if you are dealing with ObjectIds since
// new ObjectId("53fba4eb816bc772107552f0")==new ObjectId("53fba4eb816bc772107552f0")
// outputs false
return this.members.id.toString() == user.toString();
});
return user_found;
};
If user is indeed a user:
MessageBoardSchema.methods.isUserMember = function(user) {
var user_found = _.any(this.members, function(member){
// Use toString() if you are dealing with ObjectIds as explained
return this.members.id.toString() == user.id.toString();
});
return user_found;
};