Chinese Documentation : Create new models

Icon

Prerequisites:

Recommended: Read LoopBack 核心概念.

Creating models with slc loopback is quick and easy.

Recall in 创建一个简单的API step of Getting started you created a CoffeeShop model.

Now you're going to create two new models, Review and Reviewer, with the slc loopback model generator.

Icon

If you followed the previous step in the tutorial, go to Define the Review model.

If you're just jumping in, follow the steps below to catch up...

Get the app (in the state following the last article) from GitHub and install all its dependencies:

$ git clone https://github.com/strongloop/loopback-getting-started-intermediate.git
$ cd loopback-getting-started-intermediate
$ git checkout step1 
$ npm install

Define the Review model

Enter:

$ slc loopback:model

When prompted, enter or select the following:

  • Model name: Review
  • Data source: mongoDs (mongodb)
  • Base class: Use the down-arrow key to select PersistedModel.
  • Expose Reviewer via the REST API? Press RETURN to accept the default, Yes.
  • Custom plural form (used to build REST URL):  Press RETURN to accept the default, Yes.

Then, follow the prompts to add these properties:

Property nameProperty typeRequired?
datedatey
ratingnumbern
commentsstringy

To exit the model generator, press RETURN when prompted for property name.

Define the Reviewer model

Enter:

$ slc loopback:model

When prompted, enter or select the following:

  • Model name: Reviewer
  • Data source: mongoDs (mongodb)
  • Base class: Use the down-arrow key to select (custom), then when prompted to enter the base model's name, enter User.
  • Expose Reviewer via the REST API? Press RETURN to accept the default, Yes.
  • Custom plural form (used to build REST URL):  Press RETURN to accept the default, Yes.

Don't add any properties, since they are all inherited from the base User model.

To exit the model generator, press RETURN when prompted for property name.

Update boot script to add data 

Recall back in part I of Getting started, you added a boot script to create a database table from the model (via auto-migration) and add some data to the database.

Now that you have some new models and a new data source, you need to update this script so it will create data structures in MongoDB and insert data via the new models.

Copy and paste the code below into server/boot/create-sample-models.js, replacing the existing code.

This boot script has several functions:

  • createCoffeeShops() creates a MySQL table for the CoffeeShop model and adds data to the table.  This is what the create-sample-models.js script from Getting started did.
  • createReviewers() creates the Reviewer data structure in MongoDB using auto-migration and adds data to it.  
  • createReviews() creates the Reviews data structure in MongoDB using auto-migration and adds data to it.

See Creating a database schema from models for more information on auto-migration.

server/boot/create-sample-models.js
var async = require('async');
module.exports = function(app) {
  //data sources
  var mongoDs = app.dataSources.mongoDs;
  var mysqlDs = app.dataSources.mysqlDs;
  //create all models
  async.parallel({
    reviewers: async.apply(createReviewers),
    coffeeShops: async.apply(createCoffeeShops),
  }, function(err, results) {
    if (err) throw err;
    createReviews(results.reviewers, results.coffeeShops, function(err) {
      console.log('> models created sucessfully');
    });
  });
  //create reviewers
  function createReviewers(cb) {
    mongoDs.automigrate('Reviewer', function(err) {
      if (err) return cb(err);
      var Reviewer = app.models.Reviewer;
      Reviewer.create([
        {email: 'foo@bar.com', password: 'foobar'},
        {email: 'john@doe.com', password: 'johndoe'},
        {email: 'jane@doe.com', password: 'janedoe'}
      ], cb);
    });
  }
  //create coffee shops
  function createCoffeeShops(cb) {
    mysqlDs.automigrate('CoffeeShop', function(err) {
      if (err) return cb(err);
      var CoffeeShop = app.models.CoffeeShop;
      CoffeeShop.create([
        {name: 'Bel Cafe', city: 'Vancouver'},
        {name: 'Three Bees Coffee House', city: 'San Mateo'},
        {name: 'Caffe Artigiano', city: 'Vancouver'},
      ], cb);
    });
  }
  //create reviews
  function createReviews(reviewers, coffeeShops, cb) {
    mongoDs.automigrate('Review', function(err) {
      if (err) return cb(err);
      var Review = app.models.Review;
      var DAY_IN_MILLISECONDS = 1000 * 60 * 60 * 24;
      Review.create([
        {
          date: Date.now() - (DAY_IN_MILLISECONDS * 4),
          rating: 5,
          comments: 'A very good coffee shop.',
          publisherId: reviewers[0].id,
          coffeeShopId: coffeeShops[0].id,
        },
        {
          date: Date.now() - (DAY_IN_MILLISECONDS * 3),
          rating: 5,
          comments: 'Quite pleasant.',
          publisherId: reviewers[1].id,
          coffeeShopId: coffeeShops[0].id,
        },
        {
          date: Date.now() - (DAY_IN_MILLISECONDS * 2),
          rating: 4,
          comments: 'It was ok.',
          publisherId: reviewers[1].id,
          coffeeShopId: coffeeShops[1].id,
        },
        {
          date: Date.now() - (DAY_IN_MILLISECONDS),
          rating: 4,
          comments: 'I go here everyday.',
          publisherId: reviewers[2].id,
          coffeeShopId: reviewers[2].id,
        }
      ], cb);
    });
  }
};


Next: Define model relations