I'd like to use custom loopback model in server.js like below.
server/server.js
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
console.log('Web server listening at: %s', app.get('url'));
});
};
if (require.main === module) {
var server = app.start();
app.models.Foo.something(); // <- call method here
}
common/models/foo.js
module.exports = function(Foo) {
Foo.prototype.something = function() {
console.log('Hi');
return true;
};
Foo.setup = function() {
Foo.base.setup.apply(this, arguments);
};
Foo.setup();
};
ref: https://gist.github.com/bajtos/213d5dae87e19f47db5d
But actually I got a error like this.
/Projects/repo/server/server.js:45
app.models.Foo.something();
^
TypeError: Object function ModelConstructor(data, options) {
if (!(this instanceof ModelConstructor)) {
return new ModelConstructor(data, options);
}
if (ModelClass.settings.unresolved) {
throw new Error('Model ' + ModelClass.modelName + ' is not defined.');
}
ModelBaseClass.apply(this, arguments);
} has no method 'something'
at Object.<anonymous> (/Projects/repo/server/server.js:45:22)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
The method seems not to be defined. How to use custom methods in launching server and how can I correct it?
See here: http://docs.strongloop.com/display/public/LB/Working+with+LoopBack+objects.
tl;dr: The code in your model.js probably isn't loaded yet. Make sure you access the model after boot(...) is called so all the models get registered before using. Also, I'm not sure what you're trying to do in the model ie. Foo.prototype.something. If you're trying to expose something over REST, try using remote methods. See here: http://docs.strongloop.com/display/public/LB/Remote+methods.