Using Sequelize in Node.js is it possible to define a field that is calculated in the database when data is retrieved?
I understand I can add a custom getter to the DAO to calculate things in Node but that can only work on data already loaded.
My goal is to define a calculation that is run in the database and thus can use a subquery to calculate using other data.
For example, I'd ideally like to do this:
Products = Sequelize.define('Product', {
'productId': {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
'isProductActive': Sequelize.INTEGER,
'productName': Sequelize.STRING,
'productPrice': Sequelize.DECIMAL,
// This is what I don't think Sequelize supports
// but is what I ideally want to do...
'totalSales': {
type: Sequelize.DECIMAL,
subQuery: "SELECT SUM(OD.TotalPrice) FROM OrderDetails OD WHERE OD.productID = Products.productID"
}
};
Any way to do this?
For now I'm using Sequelize.query
to run custom queries but then I lose all of the functionality of Sequelize and find myself redoing what Sequelize already done. Another option I've though of is to run two queries--one fully through Sequelize for basic data and a second just to get calculated data, and then copy the calculated data to the objects in JavaScript.
What I ended up doing is creating a view inside the database and then a sequelize definition for the view, just like it was a table, and included the calculated field since it is a part of the view.
This worked fine but was not ideal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With