I am new to sequelize. I am not sure how to convert this MySql query so that I can use it in my node.js file.
MySql query:
SELECT Rtrim(Ltrim(childstatus)),TIMESTAMPDIFF(d,dob,now(3))
INTO #childstatus, #Ageday
FROM childdetails where registno=#registno
I have sequelize model for childdetails. I am not sure how to structure this query.
You can use Sequelize.fn to call these two functions indicating them in attributes option like this:
const details = await ChildDetials.findAll({
attributes: [
[Sequelize.fn('RTrim', Sequelize.fn('LTrim', Sequelize.col('childstatus'))), 'childsttaus'],
[Sequelize.fn('TIMESTAMPDIFF', Sequelize.literal('d'), Sequelize.col('dob'), Sequelize.fn('now', 3)), 'Ageday']
],
where: {
registno: registno
}
})
Related
I want to compare some case sensitive string data using sequelize. my string is "HARSH" and in db, it is "harsh" which should not be equal. I'm using where condition to find the data "HARSH" but in the response, I'm getting string data "harsh".
pReadings.user_model.findAll({
where: {
firstname: "HARSH"
}
})
The collation on the column needs to be ..._bin. It is probably ..._ci, meaning "case insensitive". It was either set that way by default or explicitly.
Please provide SHOW CREATE TABLE for assistance in changing it.
// search case insensitive nodejs usnig sequelize
const sequelize = require('sequelize');
let search = "testData"; // what ever you right here
pReadings.user_model.findAll({
where: {
firstname: sequelize.where(sequelize.fn('LOWER', sequelize.col('firstname')), 'LIKE', '%' + search.toLowerCase() + '%')
}
})
Try using the following,
pReadings.user_model.findAll({
where: sequelize.where(sequelize.fn('BINARY', sequelize.col('firstname')), 'HARSH')
// SELECT * FROM your_table WHERE BINARY(firstname) = 'HARSH';
})
For more information, check out Querying - Sequelize, under heading "Where > Basics". Good luck!
Your query is right. There is no problem with your query.
You could also try:
pReadings.user_model.findAll({
where: {
firstname: { $eq: 'HARSH' }
}
})
I have two SQL queries which i am having trouble with converting to Sequelieze Queries.
I have a model named UserTeam having columns id,team_id and isAdmin.
The first query is
Select distinct('team_id') from UserTeam where id==user.id and idAdmin==true
The second one is similar by with a little addition of group by
Select count('isAdmin') from UserTeam where id==user.id group by 'team_id';
I have written this but is incorrect:
const teamsMember = await UserTeam.findAll({where: { id: user.id, isAdmin : true}, sequelize.fn('distinct', sequelize.col('UserTeam.team_id'))});
const adminCount = await UserTeam.findAll({where: {id: user.id }, sequelize.fn('count',sequelize.col('isAdmin')), group: ['UserTeam.team_id']]});
And is there any way to get the generated query from these sequelize queries?
I have the following Employee model for a MySQL database:
var bcrypt = require('bcrypt');
module.exports = (sequelize, DataTypes) => {
const Employee = sequelize.define(
"Employee",
{
username: DataTypes.STRING,
password: DataTypes.STRING,
}, {}
);
return Employee;
};
Seeding the database is done by reading a .sql file containing 10,000+ employees via raw queries:
sequelize.query(mySeedingSqlFileHere);
The problem is that the passwords in the SQL file are plain text and I'd like to use bcrypt to hash them before inserting into the database. I've never done bulk inserts before so I was looking into Sequelize docs for adding a hook to the Employee model, like so:
hooks: {
beforeBulkCreate: (employees, options) => {
for (employee in employees) {
if (employee.password) {
employee.password = await bcrypt.hash(employee.password, 10);
}
}
}
}
This isn't working as I'm still getting the plain text values after reseeding - should I be looking into another way? I was looking into sequelize capitalize name before saving in database - instance hook
Your hooks won't be called until you use model's function for DB operation , so if you are running raw query , hooks will never be fired,
Reason : You can write anything inside your raw query , select/insert/update/delete anything , how does sequelize.js know that
it has to fire the hooks. This is only possible when you use methods
like
Model.create();
Model.bulkCreate();
Model.update();
Model.destroy;
And as per DOC raw query doesn't have hooks option to add.
And for MODEL queries you can check that it has option to
enable/disable hook.
Currently, I am building a web app with nodejs + mysql and sequelize as ORM. I want to create some views like we do in mysql, but I can't find any option in Sequelize to create views.
Is there any ORM where it's possible to create views? Or is it possible to do it with sequelize?
There are no builtin methods for managing views in Sequelize, but you can create them using plain SQL queries and manage them with normal Sequelize models.
If you're using umzug for your migrations as recommended by the Sequelize docs, you can create your view using a migration similar to this:
const view_name = 'my_view';
const query = '<SQL QUERY THAT RETURNS YOUR VIEW>';
module.exports = {
up: function (database, Sequelize) {
return database.query(`CREATE VIEW ${view_name} AS ${query}`);
},
down: function (database, Sequelize) {
return database.query(`DROP VIEW ${view_name}`);
}
}
For view changes or updates, you should use the CREATE OR REPLACE VIEW syntax to ensure you can roll back your schema changes - avoid the tempation to DROP the old view and CREATE a new one!
const view_name = 'my_view';
const original_query = '<SQL QUERY THAT RETURNS YOUR VIEW>';
const new_query = '<SQL QUERY THAT RETURNS YOUR UPDATED VIEW>';
module.exports = {
up: function (database, Sequelize) {
return database.query(`CREATE OR REPLACE VIEW ${view_name} AS ${new_query}`);
},
down: function (database, Sequelize) {
return database.query(`CREATE OR REPLACE VIEW ${view_name} AS ${original_query}`);
}
}
The exact code snippets will, of course, vary depending on how you've been setting up migrations so far.
Once your migration is all set, create a Sequelize model representing your view schema as usual, using the view name as your table name. All of the find family functions should work as expected, while update, delete, and create should be expected to fail.
You can reference the Sequelize docs for raw queries, and this example repo for using Umzug with Sequelize. The only formal documentation I can find for Umzug itself is on its NPM page.
Alright so I have a project in NodeJS where I'm utilizing Sequelize for a MySQL ORM. The thing works fantastically however I'm trying to figure out if there is a way to specify what fields are being returned on a query basis or if there's even a way just to do a .query() somewhere.
For example in our user database there can be ridiculous amounts of records and columns. In this case I need to return three columns only so it would be faster to get just those columns. However, Sequelize just queries the table for everything "*" to fulfill the full object model as much as possible. This is the functionality I'd like to bypass in this particular area of the application.
You have to specify the attributes as a property in the object that you pass to findAll():
Project.findAll({attributes: ['name', 'age']}).on('success', function (projects) {
console.log(projects);
});
How I found this:
The query is first called here: https://github.com/sdepold/sequelize/blob/master/lib/model-definition.js#L131
Then gets constructed here: https://github.com/sdepold/sequelize/blob/master/lib/connectors/mysql/query-generator.js#L56-59
Try this in new version
template.findAll({
where: {
user_id: req.params.user_id
},
attributes: ['id', 'template_name'],
}).then(function (list) {
res.status(200).json(list);
})
Use the arrays in the attribute key. You can do nested arrays for aliases.
Project.findAll({
attributes: ['id', ['name', 'project_name']],
where: {id: req.params.id}
})
.then(function(projects) {
res.json(projects);
})
Will yield:
SELECT id, name AS project_name FROM projects WHERE id = ...;
All Answers are correct but we can also use include and exclude as well
Model.findAll({
attributes: { include: ['id'] }
});
Model.findAll({
attributes: { exclude: ['createdAt'] }
});
Source