A semi-noob node guy here. In my jade templates ... I'd really love to be able to have this interface:
if currentUser.isMemberOfGroup(name)
-// dosomething
However, determining a user's membership involves interfacing with mongoose ... which is always an async'd affair. Using mongoose docs as an example I would WANT to write something along these lines (pardon me, this is written in coffee):
userSchema.methods.isMemberOfGroup = (name) ->
Club.findOne(name: name).populate({
path: 'members',
model: 'User',
match: { _id: @id }
}).exec (err, club) ->
club.members.length > 0
Is there a way I can get this method to return a bool instead of the immediate return from the exec function? What is the "right" way to design such an interface?
Here's the rest of the Club model:
clubSchema = Mongoose.Schema
name: String
hashTag: String
members: [{ type: Mongoose.Schema.Types.ObjectId, ref: 'User' }]
Does Jade support async functions (it seems it doesn't https://github.com/visionmedia/jade/issues/641)? If not, you'll have to load the value before you render your template.
This is in fact generally a good practice as it allows separation of concerns (the view should not know about the database). By the way, if you need to do a lot of async conditional logic have a look at https://github.com/olalonde/boolasync (a module I wrote). Also, if you need to do multiple database calls, I strongly recommend you use async.series or async.parallel to make your code more readable (don't go nest more than a few levels deep).