Tuesday 11 April 2017

Express.js pass model function to view layout

I am building site with Express.js and Mongoose using HandleBars view engine.I have UserSchema and RoleSchema everything is working just fine. Here is my UserSchema with function isInRole,so if user is in Role Admin it has different privileges.My problem is how can i make global variable or something like this that can be passed to layout and only if user is in Admin role to see admin panel link which is in the navbar in the layout view.I can do that by passing in every router but i want to pass it only one time to the main layout view.

let userSchema = mongoose.Schema(
{
    email: {type: String, required: true, unique: true},
    passwordHash: {type: String, required: true},
    fullName: {type: String, required: true},
    salt: {type: String, required: true},
    ads: [{type: ObjectId, ref: 'Ad'}],
    roles: [{type: ObjectId, ref: 'Role'}]
}

);

isInRole: function (roleName) {
    return Role.findOne({name: roleName}).then(role => {
        if (!role) {
            return false;
        }

        let isInRole = this.roles.indexOf(role.id) !== -1;
        return isInRole;
    })
}



via petko kostadinov

No comments:

Post a Comment