Kneel-Before-ZOD
Kneel-Before-ZOD

Reputation: 4221

Model.query() returns "undefined" error

On the Sailsjs console, I'm attempting to perform raw SQL queries using Waterline/Sails's query() method on a MySQL database. However, I keep receiving the error message:

 
sails> User.query('SELECT id from user').exec(console.log)
TypeError: Cannot call method 'exec' of undefined
    at repl:1:37
    at REPLServer.self.eval (repl.js:112:21)
    at Interface. (repl.js:239:12)
    at Interface.emit (events.js:117:20)
    at Interface._onLine (readline.js:203:10)
    at Interface._line (readline.js:532:8)
    at Interface._ttyWrite (readline.js:761:14)
    at ReadStream.onkeypress (readline.js:100:10)
    at ReadStream.emit (events.js:98:17)
    at emitKey (readline.js:1096:12)
 

Running Waterline's other methods such as find() execute successfully.

 
sails> User.find().exec(console.log)
undefined
sails> null [ { email: 'xxxx',
    password: 'xxxxx',
    name: 'xxxx',
   }]
 

Internet searches indicated that the sails-mysql adapter should be used for the connection; that's what I'm using and the issue still persists.

My config/connections.js file

 
module.exports.connections = {
  default_dev_mysql_server: {
    adapter: 'sails-mysql',
    host: '127.0.0.1',
    port: 3306,
    user: 'xxxxx',
    password: 'xxxxx',
    database: 'xxxxxx'}
}
 

My config/models.js file

 
module.exports.models = {
  schema: true,
  connection: 'default_dev_mysql_server',
  migrate: 'safe'

};
 

I'm running sails-mysql v0.11.2 and sails v0.11.2, which are the most stable versions of the software.

What other settings am I missing to be able to perform raw SQL queries on Sailsjs? Google hasn't been very helpful.

Thanks.

Upvotes: 1

Views: 201

Answers (1)

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

exec is necessary when using ORM features, as internally, it builds up a SQL statement to be execcuted at a later stage. query on the other hand, accepts a string SQL statement and a callback as its parameters, and has no use for exec, hence its undefined. Try this instead:

User.query('SELECT id from user', function(err, res){
  console.log(err, res);
});

Upvotes: 2

Related Questions