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)
Related
I'm writing a server at port 3000 and its job is to get the data from "Signup.ejs" input's values and then inserting them into the database.
All is fine but there's a problem, it says to me that TechnoBoy is an unknown column in Field list
I tried inserting "" or even `` around ${} but it didn't work well since a new error has appeared.
This is my Connection.js file that I use it to create a connection and then export it to connect it in my app's files:
let mysql = require("mysql");
let connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "something",
database: "test"
});
module.exports = connection;
And this is my Server.js that I use it to create a server and connect to the database insert the data into it:
let connection = require("./Connection.js");
let bodyParser = require("body-parser");
let express = require("express");
let app = express();
let urlencodedParser = bodyParser.urlencoded({ extended: false });
app.listen(3000, function() {
console.log("The server at port 3000 is open!");
});
app.set("view engine", "ejs");
app.get("/Signup", (req, res) => {
res.render("Register");
});
connection.connect();
app.post("/Signup", urlencodedParser, function(req, res) {
console.log(req.body);
res.render("Register");
connection.query(
`insert into users (Username, User_Password) values (${
req.body.Username
}, ${req.body.Password})`
);
});
Error I receive when I insert some data into input fields:
Error: ER_BAD_FIELD_ERROR: Unknown column 'TechnoBoy' in 'field list'
at Query.Sequence._packetToError (C:\Users\ha\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (C:\Users\ha\node_modules\mysql\lib\protocol\sequences\Query.js:77:18)
at Protocol._parsePacket (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:278:23)
at Parser.write (C:\Users\ha\node_modules\mysql\lib\protocol\Parser.js:76:12)
at Protocol.write (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\Users\ha\node_modules\mysql\lib\Connection.js:91:28)
at Socket.<anonymous> (C:\Users\ha\node_modules\mysql\lib\Connection.js:502:10)
at Socket.emit (events.js:182:13)
at addChunk (_stream_readable.js:283:12)
at readableAddChunk (_stream_readable.js:264:11)
--------------------
at Protocol._enqueue (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (C:\Users\ha\node_modules\mysql\lib\Connection.js:200:25)
at C:\Users\ha\OneDrive\Images\Documents\Projects\UI-Server\Server.js:17:14
at Layer.handle [as handle_request] (C:\Users\ha\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\ha\node_modules\express\lib\router\route.js:137:13)
at C:\Users\ha\node_modules\body-parser\lib\read.js:130:5
at invokeCallback (C:\Users\ha\node_modules\raw-body\index.js:224:16)
at done (C:\Users\ha\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\Users\ha\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:182:13)
Emitted 'error' event at:
at Connection._handleProtocolError (C:\Users\ha\node_modules\mysql\lib\Connection.js:425:8)
at Protocol.emit (events.js:182:13)
at Protocol._delegateError (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:390:10)
at Query.<anonymous> (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:153:12)
at Query.emit (events.js:182:13)
at Query.Sequence.end (C:\Users\ha\node_modules\mysql\lib\protocol\sequences\Sequence.js:78:12)
at Query.ErrorPacket (C:\Users\ha\node_modules\mysql\lib\protocol\sequences\Query.js:90:8)
at Protocol._parsePacket (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:278:23)
at Parser.write (C:\Users\ha\node_modules\mysql\lib\protocol\Parser.js:76:12)
at Protocol.write (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:38:16)
The query I used(which is in connection.query btw):
insert into users (Username, User_Password) values (${
req.body.Username
}, ${req.body.Password})
Excuse me if this is a stupid question or something, I'm very new to backend and this one is my first try on it.
I'm an idiot. I configured Password field to be int so it can't enter strings but I passed it a string, that's why when I was passing it, it was saying wrong syntax and stuff.
Oh and also, I forgot to wrap the username with "" although I still don't know how it is a problem when the property is a string itself.
Problem got solved, it can be closed now.
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)
I try to use my sails project on a server. I installed mysql.
When i call the request to create a user, sails doesn't automatically create the table "User".
I get this error:
sails-hook-sockets :: connected to Sails admin message bus.
Sending 500 ("Server Error") response:
Error (E_UNKNOWN) :: Encountered an unexpected error
: ER_NO_SUCH_TABLE: Table 'mooz.user' doesn't exist
at Query.Sequence._packetToError (/home/mooz/api/node_modules/mysql/lib/protocol/sequences/Sequence.js:48:14)
at Query.ErrorPacket (/home/mooz/api/node_modules/mysql/lib/protocol/sequences/Query.js:83:18)
at Protocol._parsePacket (/home/mooz/api/node_modules/mysql/lib/protocol/Protocol.js:271:23)
at Parser.write (/home/mooz/api/node_modules/mysql/lib/protocol/Parser.js:77:12)
at Protocol.write (/home/mooz/api/node_modules/mysql/lib/protocol/Protocol.js:39:16)
at Socket.<anonymous> (/home/mooz/api/node_modules/mysql/lib/Connection.js:92:28)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:710:14)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:382:10)
at emitReadable (_stream_readable.js:378:5)
at readableAddChunk (_stream_readable.js:143:7)
at Socket.Readable.push (_stream_readable.js:113:10)
at TCP.onread (net.js:511:21)
--------------------
at Protocol._enqueue (/home/mooz/api/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at PoolConnection.Connection.query (/home/mooz/api/node_modules/mysql/lib/Connection.js:197:25)
at __FIND__ (/home/mooz/api/node_modules/sails-mysql/lib/adapter.js:836:20)
at afterwards (/home/mooz/api/node_modules/sails-mysql/lib/connections/spawn.js:84:5)
at /home/mooz/api/node_modules/sails-mysql/lib/connections/spawn.js:40:7
at Ping.onPing [as _callback] (/home/mooz/api/node_modules/mysql/lib/Pool.js:94:5)
at Ping.Sequence.end (/home/mooz/api/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)
at Ping.Sequence.OkPacket (/home/mooz/api/node_modules/mysql/lib/protocol/sequences/Sequence.js:105:8)
at Protocol._parsePacket (/home/mooz/api/node_modules/mysql/lib/protocol/Protocol.js:271:23)
at Parser.write (/home/mooz/api/node_modules/mysql/lib/protocol/Parser.js:77:12)
at Protocol.write (/home/mooz/api/node_modules/mysql/lib/protocol/Protocol.js:39:16)
at Socket.<anonymous> (/home/mooz/api/node_modules/mysql/lib/Connection.js:92:28)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:710:14)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:382:10)
at emitReadable (_stream_readable.js:378:5)
at readableAddChunk (_stream_readable.js:143:7)
at Socket.Readable.push (_stream_readable.js:113:10)
at TCP.onread (net.js:511:21)
Details: Error: ER_NO_SUCH_TABLE: Table 'mooz.user' doesn't exist
Here my model User.js
var Waterline = require('waterline');
// Define your collection (aka model)
var User = Waterline.Collection.extend({
attributes: {
connection:'mysql',
tableName:'user',
id: {
type: 'string',
required: true,
primaryKey: true,
unique: true
},
username: {
type: 'string',
required: true
}
}
});
My model.js:
module.exports.models = {
connection: 'mysql',
migrate: 'safe'
};
My connection.js:
module.exports.connections = {
mysql: {
adapter : 'sails-mysql',
host : 'localhost',
user : 'user',
port : 3306,
password : 'test',
database : 'mooz'
}
};
And my userController
module.exports = {
createUser: function(req, res){
var params = req.params.all();
User.create({username: params.username, id: params.id}).exec(function createUser(err,created){
return res.json({
notice: 'Created user ' + params.username
});
});
}
};
I don't understand why sails can't create automatically the table, did i forget something? Is there any command to do?
Thanks.
EDIT: Resolved with dev environnement
You can try to set migrate: 'alter' in model.js, and sails lift again.
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.
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.