Search code examples
node.jssails.js

sails.js - how to list records from collections?


I am using mongodb and I have installed sails-mongodb. I can access mongodb from controller(sails.js).

Issue 1: I have created a model using sails command, but I dont know how to create function for insert, edit, list and delete. How to load the model into controller?
How to call the model functions from controller?

Issue 2: In this following controller, I store the values I intend to user in my view in 'data'. I dont know how to create db functions in model section so I have fetched some data from database using find function, but how do I assign that category values into data.list ?

 module.exports = {
 index: function (req, res) {

var data = new Object();
data.title            = "Page title";   
data.meta_keywords    = "k1,k2,k3";     
data.meta_description = "sample data";
    data.lists = "";

Category.find().done(function(err, category) {
    data.lists = category;
});

bredcrumbs = new Array();
bredcrumbs[0] = {'text':'Home','link':'Link','active':false};
res.view("pages/home",data);    

},  
   _config: {}  
};

I have created one model file with named category.js

  tableName: 'category',

  module.exports = {

    attributes: {
      name: {
          type:     'STRING',
          required: true
      },
      keyword: {
          type:     'STRING',
          required: true
      },
      image:        'STRING',
      sort_order: 'INTEGER',
      date_added: 'DATETIME',
      status:   'BOOLEAN'
     },

      toJSON: function() {
        var obj = this.toObject();
        return obj;
      }
}; 

Solution

  • To issue 1

    All valid model definitions found in the path specified via sails.config.paths.models (defaults to app/models) should be available both in the global scope and in sails.models as soon as the orm hook is initialized. Read: You do not have to load your models into your controllers manually.

    As for custom methods on sails models you have to grasp the concept of instance / model vs. class / collection methods:

    Class / Collection methods

    // models/example.js
    {
       attributes: {},
       doSomething: function() {
          // scope is not on a model here, there is none initialized
          // e.g. this.toObject() won't work
       }
    }
    

    Allows you to:

    Example.doSomething();
    

    Model / Instance methods

    // models/example.js
    {
       attributes: {
         doSomething: function() {
           // scope is on a model here
           // e.g. this.toObject() will work
         }
       },
    }
    

    Allows you to:

    Example.findOne(1).exec(function(err, example) {
      example.doSomething();
    });
    

    Documentation about collections can be found here: http://sailsjs.org/#!documentation/models Check the sections about instance and class methods.

    Applying this to your example means that you'd have to move the toJSON method into the attributes object to be called at all. But as you are doing nothing with the data in it you just could leave it out as well.

    To issue 2

    The reason for the queried Category records not reaching the view in your example is that you call res.view outside the query's callback. This should work:

    Category.find().done(function(err, categories) {
      data.lists = categories;
      res.view("pages/home",data);  
    });
    

    I guess it would make sense for you to read up on callbacks in nodejs. Starting point here on SO: Understanding callbacks in Javascript and node.js