1
votes

I want to use LoopbackJS framework to write some quick APIs.

The thing is that I want to connect my model with the mongodb loopback connector to do some simple find queries.

These are my files:

/server/model-config.js

"transaction": {
    "dataSource": "mongo",
    "public": true
}

/server/datasources.json

"mongo": {
    "name": "mongo",
    "connector": "mongodb"
}

/common/models/transaction.js

module.exports = function(Transaction) {

    Transaction.find({}, function(err, data) {
        console.log(data);
    });

};

The following is failing with this error:

Error: Cannot call transaction.find(). The find method has not been setup. The PersistedModel has not been correctly attached to a DataSource!

What am I doing wrong?

1
your code should be inside a hook ( operation, remote or connector ). docs.strongloop.com/display/public/LB/Adding+logic+to+models - Vinicius Zaramella

1 Answers

0
votes

At the moment that this code is executed

Transaction.find({}, function(err, data) {
    console.log(data);
});

The framework is not prepared to do things yet. You should register a hook callback in order to execute your business logic.

A example would be:

Transaction.observe('before save', function doStuf(ctx, next) {
   Transaction.find({}, function(err, data) {
        console.log(data);
        next();// be sure to call the callback function
   });
}

Other hooks are defined in this link:

https://docs.strongloop.com/display/public/LB/Adding+logic+to+models