xfscrypt
xfscrypt

Reputation: 276

Loopback: How to access a model from a script?

I am using Loopback and want to persist data to the database through a script.

I have written a custom command which I will be running through a cronjob:

'use strict';

var loopback = require('loopback');
var app = module.exports = loopback();
var boot = require('loopback-boot');

app.start = function() {
  return app.listen(function() {
    const baseUrl = app.get('url').replace(/\/$/, '');
    console.log('Web server listening at: %s', baseUrl);
    let Dish = app.models.dish;
    console.log(Dish);
  })
}

boot(app, __dirname, function(err) {
  if (err) throw err;

  // start the server if `$ node server.js`
  if (require.main === module)
    app.start();
});

The output I get is:

Web server listening at: http://localhost:3000
undefined

How do I access the dish model?

Upvotes: 1

Views: 1018

Answers (3)

Naimish Kher
Naimish Kher

Reputation: 294

You can access your models in loopback as below:

First of all require server.js file in your current file.

const app = require('YOUR_SERVERJS_FILE_PATH');
const MY_MODEL = app.models.YOUR_MODEL_NAME

Here, YOUR_MODEL_NAME will be as same as in name value of YOUR_MODEL.json file.

Hope you will get my point. Thank you.

Upvotes: 0

Antonio Trapani
Antonio Trapani

Reputation: 811

Build your command script like this:

let app = require('./server/server') // Set the path according on the location of your command script

app.models.YOUR_MODEL // Access the model

Upvotes: 0

user8120138
user8120138

Reputation:

You're not calling the boot function

https://github.com/strongloop/loopback-boot

The loopback-boot module initializes (bootstraps) a LoopBack application. Specifically, it:

Configures data-sources.

Defines custom models Configures models and attaches models to data-sources.

Configures application settings

Runs additional boot scripts, so you can put custom setup code in multiple small files instead of in the main application file.

Your server js likely contains something similar to this

var boot = require('loopback-boot');

app.start = function() {
    return app.listen(function() {
        const baseUrl = app.get('url').replace(/\/$/, '');
        console.log('Web server listening at: %s', baseUrl);
        if (app.get('loopback-component-explorer')) {
            const explorerPath = app.get('loopback-component-explorer').mountPath;
            console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
        }
    })
}

boot(app, __dirname, function(err) {
  if (err) throw err;

  // start the server if `$ node server.js`
  if (require.main === module)
    app.start();
});

You need these to init the app. You might be able to get away with only calling boot, but I think app.start is the one which gets your datasources connected.

Upvotes: 1

Related Questions