I have this method that performs a raw query:
Friendship.getFriends= async (userId)=>{
const result = await sequelize.query(`select id,email from users where
users.id in(SELECT friendId FROM friendships where friendships.userId =
${userId})`);
return result;
};
The result seems to contain the same exact data, but twice:
[ [ TextRow { id: 6, email: '[email protected]' },
TextRow { id: 1, email: '[email protected]' } ],
[ TextRow { id: 6, email: '[email protected]' },
TextRow { id: 1, email: '[email protected]' } ] ]
Only two records should actually be found by this query(id's 1 and 6), yet it returns an array with the same records twice.
Can somebody explain me what's going on here?
Edit: the models:
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
email: { type: DataTypes.STRING, unique: true },
password: DataTypes.STRING,
isActive:{type:DataTypes.BOOLEAN,defaultValue:true}
});
module.exports = (sequelize, DataTypes) => {
const Friendship = sequelize.define('Friendship', {
userId: DataTypes.INTEGER,
friendId: DataTypes.INTEGER,
});
The go to solution for removing duplicate rows from your result sets is to include the distinct keyword in your select statement. It tells the query engine to remove duplicates to produce a result set in which every row is unique.
Sequelize is a Node. js-based Object Relational Mapper that makes it easy to work with MySQL, MariaDB, SQLite, PostgreSQL databases, and more. An Object Relational Mapper performs functions like handling database records by representing the data as objects.
Closing the connection Sequelize will keep the connection open by default, and use the same connection for all queries. If you need to close the connection, call sequelize.close() (which is asynchronous and returns a Promise).
sequelize fails to load a model if a nested include has a where clause that returns no models.. to ensure it doesnt fail completely, you can set a required: false clause along with the where clause.. this makes sequelize return a blank array instead of failing the load completely.. Save this answer.
Try to set query type to SELECT in the second argument.
sequelize.query(queryString, {type: sequelize.QueryTypes.SELECT})
I am not sure but try below code.
const result = await sequelize.query("select id,email from users where
users.id in(SELECT friendId FROM friendships where friendships.userId =
${userId})", {type: sequelize.QueryTypes.SELECT});
One more thing : Use join instead of in
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