ASem
ASem

Reputation: 142

Can't get callback when trying to set mongoose.method

I want to assign a field from a related model to a schema using mongoose.methods in order to use it straghtforward as a property in express middleware. Method as follows:

  userSchema.methods.accountGroupOfUser = function accountGroupOfUser(callback) {
    return this.model('User')
      .findById(this.id)
      .populate( {path: 'roles.account', model: 'Account', select: 'groups'} )
      .exec(function(err, user) {
        if (err) {
          return callback(err, null);
        }
        return callback(null, user.roles.account.groups[0]);
      });
  };

and the middleware

app.use(function(req, res, next) {
  res.locals.user = {};
  res.locals.user.accountGroupOfUser = req.user && req.user.accountGroupOfUser();

  next();
});

and it returns me callback is not a function error.

I looked for various exaples with error similar to this, but it seems like it should work, I am also using functions like this in my app when when i need to make acynchronious calls to database and it works, so I really don't understand why it returns an error.

Upvotes: 2

Views: 57

Answers (1)

Steve Holgado
Steve Holgado

Reputation: 12071

Looking at your code, your 'accountGroupOfUser' function expects a callback function to be passed to it but you are not passing one.

Try this:

app.use(function(req, res, next) {
    res.locals.user = {};
    res.locals.user.accountGroupOfUser = req.user && req.user.accountGroupOfUser(function(err, group) {
        // Code here
    });

    next();
});

Upvotes: 1

Related Questions