xxxxxxxxxx
const { Sequelize, Model, DataTypes } = require('sequelize');
// Set up a Sequelize instance
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql' // Assuming MySQL as an example
});
// Define a model
class User extends Model {}
User.init({
username: DataTypes.STRING,
email: DataTypes.STRING
}, { sequelize, modelName: 'user' });
// Retrieve and display the raw SQL query
(async () => {
try {
const users = await User.findAll();
console.log(users[0].sequelize.query); // Show the raw SQL query
} catch (error) {
console.error(error);
}
})();
xxxxxxxxxx
// Callee is the model definition. This allows you to easily map a query to a predefined model
const projects = await sequelize.query('SELECT * FROM projects', {
model: Projects,
mapToModel: true // pass true here if you have any mapped fields
});
// Each element of `projects` is now an instance of Project
xxxxxxxxxx
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw: true,
})
xxxxxxxxxx
Model.findById(1).then(data => {
console.log(data.get({ plain: true }));
});
xxxxxxxxxx
const { QueryTypes } = require('@sequelize/core');
await sequelize.query('SELECT 1', {
// A function (or false) for logging your queries
// Will get called for every SQL query that gets sent
// to the server.
logging: console.log,
// If plain is true, then sequelize will only return the first
// record of the result set. In case of false it will return all records.
plain: false,
// Set this to true if you don't have a model definition for your query.
raw: false,
// The type of query you are executing. The query type affects how results are formatted before they are passed back.
type: QueryTypes.SELECT
});
// Note the second argument being null!
// Even if we declared a callee here, the raw: true would
// supersede and return a raw object.
console.log(await sequelize.query('SELECT * FROM projects', { raw: true }));
xxxxxxxxxx
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw: true,
nest: true,
})