{ sailsit }

Sails Js Tutorials for Beginners and Forum

Have a Question?

If you have any question you can ask below or enter what you are looking for!

Model Functions – Waterline | REST API

SailsJs comes with WATERLINE (ORM) pre-installed, WATERLINE provides some Model functions which are used for querying database
We will check usage of these Model functions in this tutorial with example codes

1. Create a Model names Movies using below command
sails generate model Movies

copy the below code in api/models/Movies.js file

module.exports = {

    tableName: "movies",
    autoPK: true,
    attributes: {
        movie_name: {
            type: "string"
        },
        image: {
            type: "string"
        },
        rating: {
            type: "float"
        },
        release_year: {
            type: "integer"
        },
        genre: {
            type: "string"
        },
        running_time: {
            type: 'integer'
        }
    }
};

 

2. Creating Controller

Create a controller to write functions for check all the ORM functions available with Model
Use below command to generate controller

sails generate controller Movies

 

3. ORM Functions

Copy the codes for every function and paste it in your api/controllers/MoviesController.js

  • create()
    It is used to create/insert record.
    It takes single or an array of records as input.
create: function (req, res) {
    Movies.create(req.param("movies"))
        .then(function (result) {
            return res.ok(result);
        }).catch(function (err) {
            return res.serverError(err);
        });
}

 

  • findOne()
    It is used for fetching one record and it takes search criteria object as input
findOneRecord: function (req, res) {
    Movies.findOne({"release_year": req.param("year")})
        .then(function (movie) {
            return res.ok(movie);
        }).catch(function (err) {
            return res.serverError(err);
        });
}

 

  • find()
    It is used for fetching multiple records and it takes search criteria object as input
    This function also executes without any search criteria, in that case it returns all the records present in database collection
findAllRecords: function (req, res) {
    Movies.find()
        .then(function (movies){
            return res.ok(movies);
        }).catch(function (err) {
            return res.serverError(err);
        })
}

 

  • findOrCreate()
    This is a combination of two function, this function provides a feature to search for a record and create/insert record in DB if its not already present in the database collection
    It takes two parameters as input, search cretiria object and new data object to insert
findOrCreateRecord: function (req, res) {
    Movies.findOrCreate({"movie_name": req.param("movie_name")}, req.param("movie"))
        .then(function (movie) {
            return res.ok(movie);
        }).catch(function (err) {
            return res.serverError(err);
        });
}

 

  • count()
    This function counts the records available in the database
    It takes search criteria object as input, it can also execute without any input parameter and in that case it counts all the records of the database collection
countRecord: function (req, res) {
    Movies.count()
        .then(function(moviesCount){
            return res.ok({total_movies: moviesCount});
        }).catch(function (err) {
            return res.serverError(err);
        });
}

 

  • update()
    This function is used to update any specific record by specific search criteria
    It takes input search criteria object and update data objectrespectively
updateRecord: function (req, res) {
    Movies.update({rating: req.param('from_rating')}, {rating: req.param('to_rating')})
        .then(function (updatedResult) {
            return res.ok(updatedResult);
        }).catch(function (err) {
            return res.serverError(err);
        });
}

 

  • native()
    This is a special function available in waterline only when you are working with mongoDB.
    This functions enable us to use all native mongo queries to use in SailsJs
native: function (req, res) {
    Movies.native(function(err, collection) {
        if (err) return res.serverError(err);
        collection.find({}).toArray(function (err, results) {
            if (err) return res.serverError(err);
            return res.ok(results);
        });
    });
}

 

  • query()
    This function is used for running raw queries when working with MySQL database. Since in this tutorial we are working with mongoDB we will cover this in some other tutorial
4. Creating Routes

Now let’s create routes for all these functions created in MoviesController.js
Copy the below routes and paste it in config/routes.js file

'POST /api/movies/create': 'MoviesController.create',
'GET /api/movie/:year': 'MoviesController.findOneRecord',
'GET /api/movies': 'MoviesController.findAllRecords',
'POST /api/movie/:movie_name': 'MoviesController.findOrCreateRecord',
'GET /api/movies/count/:year': 'MoviesController.countRecord',
'POST /api/movie/rating/update/:from_rating/:to_rating': 'MoviesController.updateRecord',
'GET /api/movies/mongo/native': 'MoviesController.native',

 

5. Running Sails Application

Now just run your SailsJS application and test all your created functions

You can also download the complete project from the below github url
SailsModelFunctions

One Comment

Comments are closed.