Reputation: 43491
I have
db.User.findOne({
attributes: ['id', 'firstName', 'lastName', 'email', 'phoneNumber', 'createdAt', 'type', 'status'],
where: {
id: id
}
}).then(function(dbUser) {
console.log(dbUser);
});
And it's returning all of the fields, not just the ones I specify in attributes
. What am I doing wrong?
Upvotes: 4
Views: 7192
Reputation: 19
According to official documentations:
Be aware that these attributes will not be typed, as methods such as findAll and findOne return instances of the model class.
If these attributes are part of your model, you could declare them as optional attributes on your model.
If they are not part of your model; one way to type these attributes is to use the raw option, which will return a plain object instead of an instance of the model class:
import { sql } from '@sequelize/core';
interface Data {
authorId: number;
postCount: number;
}
// this will return an array of plain objects with the shape of the "Data" interface
const data: Data[] = await Post.findAll<Data>({
attributes: [
[sql`COUNT(${sql.attribute('id')})`, 'postCount'],
],
group: ['authorId'],
raw: true,
});
Upvotes: 0
Reputation: 59
The code provided works with version 7 at least.
const user = await User.findOne({
attributes : ['id','name','email','contact'],
where: {email:req.body.email}
});
Response from postman
{
"status": "success",
"user": {
"id": 1,
"name": "admin",
"email": "[email protected]",
"contact": "0724466628"
},
}
Upvotes: 1
Reputation: 1164
According to the docs, you're doing absolutely nothing wrong. I'm seeing similar behavior. Sequelize seems to be going through some growing pains. :\
Upvotes: 2
Reputation: 40
db.animals.findOne({ },{_id:0, numlegs:1,class:1, name:1})
returns only the specific fields.
Upvotes: 0