Repository navigation
Closed
Labels
dialect: mariadbFor issues and PRs. Things that involve MariaDB (and do not involve all dialects).dialect: mysqlFor issues and PRs. Things that involve MySQL (and do not involve all dialects).type: bugDEPRECATED: replace with the "bug" issue type
Description
What are you doing?
When querying a model, which has a field with type sequelize.JSON, it returns JSON string instead of parsed JS object for that field.
// dbService.js
// Connecting to DB, params are coming from config file
export const databaseService = new Sequelize(database, user, password, {
host,
port,
dialect: 'mysql',
logging,
operatorsAliases: Sequelize.Op,
define: {
freezeTableName: true,
charset,
collate,
},
});
// models/index.js
// Creating the models
import fs from 'fs';
import path from 'path';
import sequelize from 'sequelize';
import { databaseService } from 'utils/database/dbService';
const basename = path.basename(__filename);
const db = {};
fs.readdirSync(__dirname)
.filter((file) => {
return !file.startsWith('.') && file !== basename && file !== 'index.js' && file.slice(-3) === '.js';
})
.forEach((file) => {
const fileName = path.join(__dirname, file);
const model = require(fileName).default(databaseService, sequelize);
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = databaseService;
export default db;
// models/Test.js
// Creating a Test model
export default (dbService, sequelize) => {
const Test = dbService.define('Test', {
id: {
type: sequelize.UUID,
defaultValue: sequelize.UUIDV1,
primaryKey: true,
},
data: {
type: sequelize.JSON,
},
});
return Test;
};
// test.js
// Usage in test script
import './models';
import { databaseService } from './dbService';
const newTest = await db.models.Test.create({
data: { x: 1 }
});
console.log('check 1', typeof newTest.data); // check1 object
const test = await db.models.Test.findOne({ id: newTest.id });
console.log('check 2', typeof test.data); // check 2 string
console.log('check 3', typeof test.get('data')); // check 3 stringTo Reproduce
Steps to reproduce the behavior:
- As you can see above, I'm connecting to my DB and creating model
Test, which has two fields:idanddata. The latter one is of typesequelize.JSON. - Then in my test script, I create an instance of
Testmodel, providing JS object fordatafield. On the next line when I print type ofdata, it prints correctlyobject. - However, when I query that object using
findOne(no difference how you query), the returned object'sdatafield isstringnow.
What do you expect to happen?
I expect to get a parsed JS object out of my JSON field.
What is actually happening?
I'm getting JSON string instead of object.
Environment
Dialect:
- mysql
- postgres
- sqlite
- mssql
- any
Dialect library version: mysql2 - 1.6.4
Database version: mysql Ver 15.1 Distrib 10.3.14-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2 (The DB is run in Docker using official MariaDB image)
Sequelize version: 4.41.2
Node Version: v10.15.2
OS: macOS Mojave, 10.14.3 (18D109)
Tested with latest release:
- No
- Yes, specify that version:
Reacted by Vasiliy Vanchuk, misos1, Hayk, Mark Edington, Jason and JoeXaviCol
Metadata
Metadata
Assignees
Labels
dialect: mariadbFor issues and PRs. Things that involve MariaDB (and do not involve all dialects).dialect: mysqlFor issues and PRs. Things that involve MySQL (and do not involve all dialects).type: bugDEPRECATED: replace with the "bug" issue type
Activity
kishmiryan-karlen commentedon May 13, 2019
Also, I found this test in your repo https://github.com/sequelize/sequelize/blob/master/test/integration/model/json.test.js#L771, where you get the JS object using
get()method, however that also returns string for me.And in your code here https://github.com/sequelize/sequelize/blob/master/lib/data-types.js#L514, I couldn't find anywhere, where do you parse the JSON string into an object.
vvscode commentedon May 13, 2019
I wonder - if about the idea - does that types only for writing? or should work for read also?
Is there a documentation about inner interfaces (Like abstract type and so on)?
kishmiryan-karlen commentedon May 23, 2019
@sushantdhiman any feedback on this?
misos1 commentedon May 23, 2019
It should JSON.parse it like for example mariadb dialect does.
vvscode commentedon May 23, 2019
@misos1 can you provide a link to a code which does this?
misos1 commentedon May 23, 2019
Check
node_modules/sequelize/lib/dialects/mariadb/query.jsfunctionhandleJsonSelectQuery. I was able to find JSON.parse also in sqlite dialect but not in others. Sequelize.JSON is new type so maybe this was overlooked or probably other dialects have connectors which directly support JSON type (except mysql2 probably).vvscode commentedon May 24, 2019
@kishmiryan-karlen
http://docs.sequelizejs.com/manual/dialects.html#mariadb
kishmiryan-karlen commentedon May 26, 2019
@vvscode Looks like it's a V5 feature, because on V4 I'm getting this:
Error: The dialect mariadb is not supported. Supported dialects: mssql, mysql, postgres, and sqlite.ddolcimascolo commentedon May 30, 2019
Hi @kishmiryan-karlen,
Just asking, is you table created by sequelize? Cause I don't see a call to
syncin your code sample above. If not, any chance your column in the DB isn't a JSON column?We're upgrading to sequelize 5 here but have used v4 for more than a year with Mysql JSON columns a lot, and parsing/serialization works flawlessly...
David
misos1 commentedon May 31, 2019
@ddolcimascolo Your tables were probably not created by sequelize v4 nor v5 and I doubt that older version of sequelize created JSON columns. Sequelize will for some reason create mysql LONGTEXT type in db when you use Sequelize.JSON. If you already have mysql JSON column in db then I do not doubt it is working because seems mysql2 connector supports JSON columns and I saw calls to JSON.parse in sources so it will directly return JS object to sequelize and sequelize in this case does not must parse string.
ddolcimascolo commentedon May 31, 2019
@misos1
You got me puzzled... All my Mysql tables are created through migration scripts (applied with https://github.com/sequelize/umzug) using sequelize query interface, here's one for your reference:
DataTypesisSequelize.DataTypesin the above scripts, andqiissequelize.getQueryInterface().The resulting table indeed has a
JSONcolumn. Mysql version is 5.7.26misos1 commentedon Jun 1, 2019
Ok seems this problem is here only when using mysql dialect with mariadb database, not with mysql database.
https://mariadb.com/kb/en/library/json-data-type/
ddolcimascolo commentedon Jun 1, 2019
OK, thus the new
mariadbdialect...This issue can probably be closed then, if everyone agrees.
misos1 commentedon Jun 1, 2019
This is not so simple. Mariadb dialect is still new and has bugs which prevents to use it as direct replacement in already existing projects based on mysql dialect. It was added in sequelize v5. This bug should be easy to fix. Sequelize or mysql dialect could detect that it got string instead of JS object and simply parse it.
https://github.com/sequelize/sequelize/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+mariadb
ddolcimascolo commentedon Jun 2, 2019
Yeah, I got your point but on the other hand I believe MariaDB wasn't supported on v4 (or was it?)
23 remaining items
aaron-syed commentedon May 4, 2020
Hey, sorry to revive this, but do we got any progress on this matter?
I was trying a JSON field on a Mysql 5.7.29 ( Ubuntu 18 ) with Sequelize 5.21.7 and has no luck with it.
When I try to update a model that has a JSON field, the field is still empty after I save it, even though I got no errors. The process goes on smoothly.
Kinda frustrating.
miladmeidanshahi commentedon May 9, 2020
@omegascorp I have the same problem when including some model, JSON fields convert to strings thas so bad.
aaron-syed commentedon May 9, 2020
Sorry, I didn't update ya guys.
Turned out I was the blame.
the fact is that I was trying to update the wrong model. Shame on me.
As soon as i switched to the right one.. ta dah! it worked.
And it is still working like a charm ever since!
medington commentedon Jul 15, 2020
@papb I see you re-opened this issue in August 2019. Is there any expectation that a future release of Sequelize will seamlessly provide the required
JSON.parse()when using the MySQL dialect with a MariaDB?Also, if there is a suggested method to patch / workaround the issue by adding code into the model or into an event handler that would be very much appreciated. Thanks!
miladmeidanshahi commentedon Sep 12, 2020
@medington Apparently there is no alternative yet
github-actions commentedon Nov 10, 2021
This issue has been automatically marked as stale because it has been open for 14 days without activity. It will be closed if no further activity occurs within the next 14 days. If this is still an issue, just leave a comment or remove the "stale" label. 🙂
tobiasvorhoff commentedon Mar 18, 2022
Is there anything new on this issue? I'm also stuck with the same problem.
diewolke9 commentedon Apr 30, 2022
Struggling with the same here. One workaround would be to create getters and setters, but they will not trigger if the object is a nested child of a find() with associations.
alexstep commentedon Jun 10, 2022
Same problem
IonelLupu commentedon Sep 7, 2022
Still a problem. I am using MySQL database with MySQL dialect. I also use sqluelize-typescript:
I had to do this instead:
Edit
The above works when you want to select the data but I just found out it doesn't work when I want to save the data. I added these:
But now I get
Field 'scopes' doesn't have a default value. This is incredible. How can it not have a default value when I can clearly see the getter and the setter called?parsadoc commentedon Jan 3, 2023
In my case, I used MySql DB on the MariaDB driver!
you can change sequelize
dialectto MariaDBalso you need to install mariadb package
npm install mariadb --saveor
yarn add mariadb --saveit worked for me.
adamleemiller commentedon May 2, 2024
Either there are still some problems here or I am doing something completely incorrect.
I am using Sequelize 6.37.0. I have a column in a database table named
extrawhich is of typeLONGTEXT. The underlying database engine isMariaDB 10.11.7running via anAWS RDS instancewhich doesNOTsupport the JSON native column type.When I create a new row, the row is created successfully and the JSON object is stored correctly. However, if I update the row with the same data, the object is then stringified. For example, it is going from
{"country_codes":["US"]}to"{\"country_codes\":[\"US\"]}"which is not what I am expecting. I have tried using agetterand asetterbut that causes other issues.Scenario 1:
Row Creation: OK
Row Update: Automatically stringified
Row Get: extra column is a string
Scenario 2: Let’s try to fix the Row Get from returning a string to instead, returning an object.
Row Creation: Fails - uncaughtException: \“[object Object]\” is not valid JSON
Row Update: Cannot update since creation did not work
Row Get: Cannot get since creation did not work
Scenario 3: Remove the get and try to fix the update row from storing a stringified object
Row Creation: Fails - SyntaxError: \“[object Object]\” is not valid JSON
Row Update: Cannot update since creation did not work
Row Get: Cannot get since creation did not work
Scenario 4: Change DataType to TEXT
Row Creation: Fails - SequelizeValidationError: string violation: extra cannot be an array or an object
Row Update: Cannot update since creation did not work
Row Get: Cannot get since creation did not work
Basically what I am after is when I create a new row, the
extracolumn is stored as anobjectand when I update the row, theextracolumn should stay an object whether I pass new data or existing data (which is always a JSON object). When IfindorfindAll, theextracolumn should be a parsed object, not a string.The following works to create, update and get however, because the type is
TEXTwhich means I cannot search the JSON object in a WHERE clause:Query
Error
If I change the data type to JSON, the query and where clause work fine however now the data in the extra column is stringified again.
Any help is greatly appreciated.