Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 127 Vote(s) - 3.69 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Specifying specific fields with Sequelize (NodeJS) instead of *

#1
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.
Reply

#2
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:

[To see links please register here]

<br/>
Then gets constructed here:

[To see links please register here]

Reply

#3
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 = ...;
Reply

#4
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][1]


[1]:

[To see links please register here]

Reply

#5
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);
})
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through