this is my first time using sails.js with mySQL database and I'm really confused about this error.
I have a controller & model called 'company'. It relates to table 'company' in mySQL database. The table itself has one-to-many associations with two tables called 'module' and 'user' (each user/module must connect with one company id). I've set the foreign key in the MySQL database.
The problem is.. each time I open any page/action from this controller, there is this error:
error: Sending 500 ("Server Error") response:
Error (E_UNKNOWN) :: Encountered an unexpected error
: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'where clause'
at Query.Sequence._packetToError (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Sequence.js:30:14)
at Query.ErrorPacket (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Query.js:82:18)
at Protocol._parsePacket (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Protocol.js:213:24)
at Parser.write (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Parser.js:62:12)
at Protocol.write (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Protocol.js:37:16)
at Socket.<anonymous> (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/node_modules/mysql/lib/Connection.js:75:28)
at Socket.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:764:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:426:10)
--------------------
at Protocol._enqueue (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Protocol.js:110:48)
at PoolConnection.Connection.query (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/node_modules/mysql/lib/Connection.js:166:25)
at PoolConnection.liveConnection.query (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/lib/connections/spawn.js:98:16)
at __FIND__ (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/lib/adapter.js:836:20)
at afterwards (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/lib/connections/spawn.js:104:5)
at /Users/alanyudh/Sites/matta/node_modules/sails-mysql/lib/connections/spawn.js:40:7
at Pool.<anonymous> (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/node_modules/mysql/lib/Pool.js:51:14)
at Handshake.Sequence.end (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Sequence.js:78:24)
at Handshake.Sequence.OkPacket (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Sequence.js:87:8)
at Protocol._parsePacket (/Users/alanyudh/Sites/matta/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Protocol.js:213:24)
Details: Error: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'where clause'
This is my company model:
module.exports = {
attributes: {
name:{
type:"string",
required:true,
unique:true,
minLength: 2
},
type:{
type:"string",
enum: ['hq','sub'],
defaultsTo: 'hq'
},
desc:{
type:"text",
required:true
},
logo: {
type: 'string'
},
address: {
type: 'text'
},
city: {
type: 'string'
},
region: {
type: 'string'
},
country: {
type: 'string'
},
zipcode: {
type: 'string'
},
phone_number: {
type: 'string'
},
website: {
type: 'string'
}
},
};
I have tried using 'autoPK: false', 'schema: true', add 'columnName/fieldName', but none of them is working.
What is the error means?
How do I fix it?
Thank you very much.
Oppening localhost:1337/company/index is your problem not any mysql or other orm problem!
This is a route config probem. When you open this URL the default sails behavior is that you try to access a specific company record through the default REST api. Check the default rest routes behavior.
To be more explicit in your case sails interpret that you are querying a specific company with the id "index" which is not a number NaN thus you get this error.
RESTful routes, where the path is always /:modelIdentity or /:modelIdentity/:id.
I do NOT have the exact answer, to your specific case, BUT, I need to point to you and at the same time ventilate here my frustration, that it is a pathetic notorious problem of various APIs, when they do not address the cause of an error specifically enough, and just let the exception stack lazily bubble out to the next error handler. This often will be completely misleading the developer about the cause of the actual exception. So be VERY mindful that the error text you see may be pretty much OFF the actual issue. Well, at least you know there is a problem. Now you have to use your own wits and endless variations or approaches to figure it out.
Related
Server: Sailsjs
Database: mysql
Node Library used: sails-mysql(0.11.5)
I am trying to insert a data in mysql from sailsjs node server.
Data to be inserted:
{
"first_name": "Admin Testing",
"last_name": "User",
"email": "admin14#testing.com",
"role_id": 8
}
Where role_id is having a foreign key relation to model role.
Here the role_id : 8 doesn't have value in role table. So while inserting, it is throwing the error. But that error we couldn't console or json.stringify since the following error occurs:
TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
at /var/www/aitachatbot/server/api/controllers/UserController.js:38:42
at wrapper (/var/www/aitachatbot/server/node_modules/waterline/node_modules/lodash/index.js:3602:19)
at applyInOriginalCtx (/var/www/aitachatbot/server/node_modules/waterline/lib/waterline/utils/normalize.js:421:80)
at wrappedCallback (/var/www/aitachatbot/server/node_modules/waterline/lib/waterline/utils/normalize.js:331:16)
at error (/var/www/aitachatbot/server/node_modules/switchback/lib/normalize.js:42:31)
at _switch (/var/www/aitachatbot/server/node_modules/switchback/lib/factory.js:56:28)
at /var/www/aitachatbot/server/node_modules/sails-hook-validation/lib/create.js:66:21
at /usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/query/dql/create.js:223:14
at wrapper (/usr/local/lib/node_modules/sails/node_modules/lodash/index.js:3592:19)
at applyInOriginalCtx (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:421:80)
at wrappedCallback (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:335:16)
at error (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/normalize.js:42:31)
at _switch (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/factory.js:56:28)
at afterwards (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/adapter/dql.js:87:16)
at wrapper (/usr/local/lib/node_modules/sails/node_modules/lodash/index.js:3592:19)
at applyInOriginalCtx (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:421:80)
at wrappedCallback (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:335:16)
at error (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/normalize.js:42:31)
at _switch (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/switchback/lib/factory.js:56:28)
at sendBackError (/var/www/aitachatbot/server/node_modules/sails-mysql/lib/connections/spawn.js:97:11)
at Object.poolfully [as releaseConnection] (/var/www/aitachatbot/server/node_modules/sails-mysql/lib/connections/release.js:28:12)
at /var/www/aitachatbot/server/node_modules/sails-mysql/lib/connections/spawn.js:90:37
at Query._callback (/var/www/aitachatbot/server/node_modules/sails-mysql/lib/adapter.js:395:27)
at Query.Sequence.end (/var/www/aitachatbot/server/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)
at Query.ErrorPacket (/var/www/aitachatbot/server/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Query.js:94:8)
at Protocol._parsePacket (/var/www/aitachatbot/server/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Protocol.js:280:23)
at Parser.write (/var/www/aitachatbot/server/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Parser.js:73:12)
How can we handle this error in sailsjs?
In theory, you don't want these errors to ever show up in production... even if they did, the full json dump of the error object probably is not something a run-of-the-mill user wants to see.
You may also be asking about how to get full info out of this error while debugging. I guess the good news there is, you seem to already know the root cause of your error!
The error objects we have in node can have pretty different structures depending where they come from, but I have yet to encounter an error that does not have smart casting of the errors to strings. That means that even if console.log(err) fails, something like: console.log('Got an error: ' + err) will likely work, casting the error to a string.
The code could be something like this:
User.create({
"first_name": "Admin Testing",
"last_name": "User",
"email": "admin14#testing.com",
"role_id": 8
}).exec(function(err, createdUser) {
if (err) {
var readableErr = '' + err;
console.log('Error creating user: ' + readableErr);
// return something the client will recognize and interpret
// you can use http error codes, or your own conventions
return res.send({
success: false,
message: readableErr
});
}
// do something with createdUser...
});
I'm currently trying to do an inner join between two tables:
The first one is in a database called SmartMonument while the second one is in a database called SmartMonumentCB.
Here is the code for the init of those table:
In 'database.js' (referring to SmartMonument):
const CompaniesForClient=sequelize.define('cfc', {
scrapperName: {type: Sequelize.STRING, allowNull: false},
clientID: {type: Sequelize.INTEGER(10), allowNull: false}
});
CompaniesForClient.sync();
module.exports = { sequelize, CompaniesForClient };
The second table is :
const Companies = sequelize.define('companies', {
scrapperName: {type: Sequelize.STRING, allowNull: false},
scrapperAddress: {type: Sequelize.STRING(500)}
});
Companies.sync();
module.exports = {sequelize, Companies};
Both tables are well created and then I try to add something so both tables are related on the scrapperName field.
I try to do it like such:
CompaniesForClient.hasOne(CompaniesDB.Companies, {foreignKey: 'scrapperName'});
My goal is ultimatly to be able to read all the CompaniesForClient fields with all the fields of Companies in one request like such:
CompaniesForClient.findAll({where:{clientID: param}, include: [{model: Companies}];
Right now I get the following error :
Unhandled rejection SequelizeDatabaseError: Cannot add foreign key constraint
at Query.formatError(/home/ubuntu/backendDev/node_modules/sequelize/lib/dialects/mysql/query.js:222:16)
at Query.connection.query [as onResult] (/home/ubuntu/backendDev/node_modules/sequelize/lib/dialects/mysql/query.js:55:23)
at Query.Command.execute (/home/ubuntu/backendDev/node_modules/mysql2/lib/commands/command.js:30:12)
at Connection.handlePacket (/home/ubuntu/backendDev/node_modules/mysql2/lib/connection.js:515:28)
at PacketParser.onPacket (/home/ubuntu/backendDev/node_modules/mysql2/lib/connection.js:94:16)
at PacketParser.executeStart (/home/ubuntu/backendDev/node_modules/mysql2/lib/packet_parser.js:77:14)
at Socket.<anonymous> (/home/ubuntu/backendDev/node_modules/mysql2/lib/connection.js:102:29)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at addChunk (_stream_readable.js:266:12)
at readableAddChunk (_stream_readable.js:253:11)
at Socket.Readable.push (_stream_readable.js:211:10)
at TCP.onread (net.js:585:20)
Make sure that your foreign key (if not primary) is unique and also check if the data in your database is matching with the data from the table that you are going to associate it with (of course in the foreign key column)
Here are my model objects and get method.
model objects:models.js
var Client = sequelize.define("Client", {
name: DataTypes.STRING(100),
status : DataTypes.STRING(1)
});
var Lob = sequelize.define("Lob", {
name : DataTypes.STRING(100),
status : DataTypes.STRING(1)
});
Lob.belongsTo(Client, { constraints: true, foreignKeyConstraint:true });
Get method:
router.get('/getlobs', function(req, res) {
models.Lob.find({ where: { "id": 2000 }, include: [models.Client], attributes:["id", "name", "status"]}).then(function(lobs) {
return res.send(lobs);
});
});
With out include it works fine to get required attributes,while I am trying to get include Client model getting the error.Actually my intention to get client name insted of ClientId using foreign key relation.
Query:
Executing (default):
SELECT `Lob`.`id`, `Lob`.`name`, `Lob`.`status`, `Client`.`id`
AS `Client.id`, `Client`.`Client_Name`
AS `Client.Client_Name`, `Client`.`Address`
AS `Client.Address`, `Client`.`Status`
AS `Client.Status`, `Client`.`Created_By`
AS `Client.Created_By`, `Client`.`createdAt`
AS `Client.createdAt`, `Client`.`updatedAt`
AS `Client.updatedAt` FROM `Lobs`
AS `Lob` LEFT OUTER JOIN `Clients`
AS `Client` ON `Lob`.`ClientId` = `Client`.`id` WHERE `Lob`.`id` = 2000;
Error:
Unhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'Client.Client_Name' in 'field list'
at Query.formatError (/home/mobi/QA/qa/node_modules/sequelize/lib/dialects/mysql/query.js:175:14)
at Query._callback (/home/mobi/QA/qa/node_modules/sequelize/lib/dialects/mysql/query.js:49:21)
at Query.Sequence.end (/home/mobi/QA/qa/node_modules/mysql/lib/protocol/sequences/Sequence.js:86:24)
at Query.ErrorPacket (/home/mobi/QA/qa/node_modules/mysql/lib/protocol/sequences/Query.js:88:8)
at Protocol._parsePacket (/home/mobi/QA/qa/node_modules/mysql/lib/protocol/Protocol.js:280:23)
at Parser.write (/home/mobi/QA/qa/node_modules/mysql/lib/protocol/Parser.js:75:12)
at Protocol.write (/home/mobi/QA/qa/node_modules/mysql/lib/protocol/Protocol.js:39:16)
at Socket.<anonymous> (/home/mobi/QA/qa/node_modules/mysql/lib/Connection.js:103:28)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:153:18)
at Socket.Readable.push (_stream_readable.js:111:10)
at TCP.onread (net.js:536:20)
What kind of error is this?
Unhandled rejection SequelizeDatabaseError: ER_EMPTY_QUERY: Query was empty
at Query.formatError (node_modules/sequelize/lib/dialects/mysql/query.js:159:14)
at Query._callback (node_modules/sequelize/lib/dialects/mysql/query.js:35:21)
at Query.Sequence.end (node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)
at Query.ErrorPacket (node_modules/mysql/lib/protocol/sequences/Query.js:94:8)
at Protocol._parsePacket (node_modules/mysql/lib/protocol/Protocol.js:274:23)
at Parser.write (node_modules/mysql/lib/protocol/Parser.js:77:12)
at Protocol.write (node_modules/mysql/lib/protocol/Protocol.js:39:16)
at Socket.<anonymous> (node_modules/mysql/lib/Connection.js:96:28)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
at Socket.Readable.push (_stream_readable.js:126:10)
at TCP.onread (net.js:538:20)
I'm trying to update an entity with the following code:
db.Account.update({
'post_id': data.id
}, {
where: { id: account.id }
})
.spread(account => {
next();
});
but it doesn't work. Any idea?
The same issue I was facing and after a lot of debugging found out the silly mistake. The reason for me was in mysql added a column and forgot to add the same to sequelize model representing the same table so for your case also will suggest you to just double check for post_id is present in Account sequelize model.
When trying to use sails-mysql I get an ER_NO_DB_ERROR: No database selected exception.
Even though I followed all the instructions I was able to find as closely as possible. I also looked into related issues:
Sailsjs - How to use mySQL
https://github.com/balderdashy/sails/issues/632
http://dustinbolton.com/error-er_no_db_error-no-database-selected/
Nothing seemed to help so far.
This is what I am doing:
I started out with a fresh project:
sails new sql-test
cd sql-test
Installed sails-mysql
sudo npm install sails-mysql
I changed the config:
// config/adapters.js
module.exports.adapters = {
'default': 'mysql',
mysql: {
module : 'sails-mysql',
host : 'localhost',
port : 3306,
user : 'root',
password : 'superSecret',
database : 'testDB'
}
};
Created a Model:
// api/models/User.js
module.exports = {
attributes: {
name: 'string'
}
};
And when I try to run it from the project's root:
sails lift
I get the following:
Logic error in mySQL ORM.
{ [Error: ER_NO_DB_ERROR: No database selected] code: 'ER_NO_DB_ERROR', index: 0 }
error: Hook failed to load: orm (Error: ER_NO_DB_ERROR: No database selected)
error: Error encountered while loading Sails core!
error: Error: ER_NO_DB_ERROR: No database selected
at Query.Sequence._packetToError (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Sequence.js:32:14)
at Query.ErrorPacket (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Query.js:82:18)
at Protocol._parsePacket (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Protocol.js:172:24)
at Parser.write (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Parser.js:62:12)
at Protocol.write (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Protocol.js:37:16)
at Socket.ondata (stream.js:51:26)
at Socket.EventEmitter.emit (events.js:117:20)
at Socket.<anonymous> (_stream_readable.js:746:14)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
at Socket.Readable.push (_stream_readable.js:127:10)
at TCP.onread (net.js:526:21)
--------------------
at Query.Sequence (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Sequence.js:15:20)
at new Query (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Query.js:12:12)
at Function.Connection.createQuery (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/Connection.js:48:10)
at Connection.query (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/Connection.js:100:26)
at __DESCRIBE__ (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/lib/adapter.js:121:20)
at afterwards (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/lib/adapter.js:571:7)
at Handshake._callback (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/lib/adapter.js:549:9)
at Handshake.Sequence.end (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Sequence.js:66:24)
at Handshake.Sequence.OkPacket (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/protocol/sequences/Sequence.js:75:8)
at Protocol._parsePacket (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Protocol.js:172:24)
at Parser.write (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Parser.js:62:12)
at Protocol.write (/home/tster/Documents/sandbox/sql-test/node_modules/sails-mysql/node_modules/mysql/lib/protocol/Protocol.js:37:16)
at Socket.ondata (stream.js:51:26)
at Socket.EventEmitter.emit (events.js:117:20)
at Socket.<anonymous> (_stream_readable.js:746:14)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
at Socket.Readable.push (_stream_readable.js:127:10)
at TCP.onread (net.js:526:21)
Additional Information:
sails v0.9.13
sails-mysql (v0.9.9)
mysql v14.14 Distrib 5.5.34, for debian-linux-gnu (x86_64) using readline 6.2
I can connect the the database via command line.
I am able to connect and query the Database when using node-mysql
Could anybody give me some advice? Am I missing something? Anything else I should check out?
I just hit this same problem. In order to get it to work, I had to add the adapter configuration information to my model, e.g. /api/models/User.js:
module.exports = {
adapter: 'mysql',
config: {
host: 'localhost',
user: 'user',
port:'3306',
// Psst.. You can put your password in config/local.js instead
// so you don't inadvertently push it up if you're using version control
password: 'secret',
database: 'sailstest'
},
attributes: {
firstName: 'STRING'
}
};
See the docs:
http://sailsjs.org/#!documentation/models
I also had to add /api/controllers/UserController.js manually, as the generate function did not add it on this app, although it did add it on the previous test app I made.
UPDATE:
Install the Sails.js beta to get better functionality.
npm install sails#beta -g
Not only does the config actually work as expected (under config/connections.js), the ORM features support associations, which are not supported in the 0.9 release.
I know this question already has an answer, but it's more of a workaround. This is what fixed the same issue for me.
Changing the default adapters.js file mysql adapter object from myLocalMySQLDatabase to simply mysql seemed to fix it for me.
Hope this helps.
You may get this error when the .env file is not in the same directory.
You can check what the error is with the following code:
const result = require('dotenv').config();
if (result.error) {
console.log(result.error)
}
console.log(result.parsed)
You must take care about data type.
if you have module like this
module.exports = {
attributes: {
name: 'string'
}
};
In database under modal name table field name must be varchar.
My database field is set to text and I getting this error , when change it to varchar everything work.