Search code examples
loopbackjs

Is it possible to do models.find() inside a remote hooks?


I have a question about loopback js, specifically Loopback 3. Is it possible to do a models.find() operation inside a remote hooks?

I tried to make a models.find() request inside a afterRemote() remote hooks, however I don't know how to get the response of that find() or even know if the operation is successful.

module.exports = function(User) { 
const app = require('../../server/server');
const models = app.models;

User.afterRemote('find', function(context, user, next){
    models.saldo_cuti.find(function(err){
      if (err) throw (err);
      return next(); //this only return regular User.find()
    });
  })
}

I want to be able to manipulate that models.saldo_cuti.find() result, however I can't seems to find how to do that.


Solution

  • Your model objects and their methods and such can be run anywhere. Being inside of that operation hook doesn't change them.

    It looks like you're just not doing anything with the result. function(err) is missing function(err, result). FYI you can use async/await to make this stuff even easier to work on:

    module.exports = function(User) { 
    
        User.afterRemote('find', async (context, user) => {
            const docs = await User.app.models.saldo_cuti.find();
            // do something with docs, or apply a filter to find() to limit results.
        });
    
    };