Search code examples
mysqlsails.jsschemamodels

can i connect to mysql database from sails without defining models?


I'm using sails.js and sails-MySQL and I want to connect to a MySQL database. I have tables, functions, and procedures in my workbench. now I want to know that is it necessary to create model files and define my schema again?


Solution

  • Yes, you can connect to your DB without defining models. However bare in mind that you will have to write raw queries every time. So first you need to define your DB connection in your datastores.js file. Then you can do the following in some of your controllers when you want to get something from your DB (say you have a table users and you want to get all of them):

      var myDBStore = sails.getDatastore(); //gets the default datastore.
      var query = "SELECT * FROM users;";
    
      myDBStore.sendNativeQuery(query).exec(function (err, nativeResult) {
        if (err) {
           return res.send(err);
        }
        return res.send(nativeResult.rows);
      });
    

    or using the modern way in an async function:

      var myDBStore = sails.getDatastore(); //gets the default datastore.
      var query = "SELECT * FROM users;";
      var nativeResult;
    
      try {
        nativeResult = await myDBStore.sendNativeQuery(query);
      } catch (err) {
        return res.send(err);
      }
    
      return res.send(nativeResult.rows);
    

    More info here: https://sailsjs.com/documentation/reference/waterline-orm/datastores in section "Using datastores without a model"