Sequelize "SELECT * from tablename" query - node.js

Why the query below executes SELECT id, email, name FROM users AS users WHERE users.email = 'admin#admin.com'; rather than SELECT * from users WHERE email = admin#admin.com ?
http://docs.sequelizejs.com/en/latest/docs/querying/#where
Documentation states that it'll run a SELECT * query when I do findAll(), but it does something different in my example. What's missing here?
Here's my users model.
var user = sequelize.define('users', {
id : {
type : Sequelize.INTEGER,
primaryKey : true,
autoIncrement : true
},
email : {
type : Sequelize.STRING
},
name : {
type : Sequelize.STRING
}
},
{
tableName: 'users',
freezeTableName: true
});
And this is my query. It seems that it only selects defined columns, but I don't want this.
var email = "admin#admin.com";
user.findAll({where: {email: email}}).then(function (user) {
res.send(user);
}).error(function (err) {
console.log("Error:" + err);
});

This is expected behavior of sequelize selecting only the columns which you have defined. If you want to select all of the columns using sequelize you must define them in your model.

Related

How to delete associated rows with sequelize

I am trying to delete rows associated with a row in a table, without deleting the main row (thus can't use CASCADE).
This is the raw PostgreSQL query that does what I want to achieve with SQL. Is sequelize able to generate such query:
DELETE FROM session USING user WHERE session.user_id = user.id AND user.username = 'bob'
The model is (not including irrelevant columns):
create table user (
id uuid primary key default uuid_generate_v4(),
username text UNIQUE NOT NULL
);
create table session (
id uuid primary key default uuid_generate_v4(),
user_id uuid NOT NULL references user(id) ON DELETE CASCADE
);
The association is defined in sequelize as:
Session.belongsTo(models.User, {
foreignKey: "user_id"
});
User.hasMany(models.Session, {
foreignKey: "user_id"
});
An alternative version of the query could be:
DELETE FROM session WHERE session.user_id = (SELECT user_id FROM user WHERE username = 'bob');
But I think sequelize doesn't handle subqueries yet?
I tried something along the lines:
return Session.destroy({
include: [
{ model: User, where: { username: 'bob' }}
],
truncate: false
});
However, sequelize complains:
Error: Missing where or truncate attribute in the options parameter of model.destroy.
If anyone gets here, this is how I "delete associated rows with sequelize": little help from the library:
Read the user from db (Users.findOne({ ... }))
call the method setSessions(array) provided by sequelize (the name depends on your model) which returns a promise.
/** #param {string} username */
const clearUserSessions = async (username) {
const userInstance = await Users.findOne({
where: { username },
include: ['sessions']
})
if (!userInstance) {
/* user not found */
return ...
}
await userInstance.setSessions([])
/* removed every session from user */
return ...
};
later:
try {
await clearUserSessions('bob')
} catch(err) {
...
}
return Session.destroy({
where: {
'$users.username$': 'bob'
},
include: [{
model: User,
as: 'users'
}],
});
Hope that helps. Try to reach me with comment.

How to return the result set of sequelize query in camel case fashion?

I have defined a table schema in the database in an underscored fashion but I want to return the result set API response in camel case fashion. I know I can process the underscored object returned by sequelize and convert it into camelcase fashion. Is there any functionality to return the response of a query in camelcase fashion in sequelize itself?
To archieve this you need to use field when defining your model.
module.exports = (sequelize, DataTypes) => {
const yourTable = sequelize.define('yourTable', { // table name use it for Sequelize
camelCase: { //camelCase name that you'll use with sequelize.
field: 'under_score', //underscore name on yor database.
type: DataTypes.STRING
},
keyId: { //need to the same with association
field: 'key_id',
type: DataTypes.INTEGER
},
}, {
tableName: 'your_table', // then name of the table on the db
underscored: true,
});
yourTable.associate = (models) => {
yourTable.belongsTo(models.otherTable, {
as: 'Something',
foreignKey: 'key_id', //put attention here and keyId above.
onDelete: 'cascade'
});
}
}

How to write a query in dynamo db with a conditioned expression

I want to query a dynamo db table for getting company id but the same table need a hash key so my query is something like this.
var optsq = {
'ConsistentRead': true,
'AttributesToGet': ['companyid'],
TableName : usertable,
Key : {
"userid" : {
"S" : usrname
},
"comapnyid" :{
"S":''
}
}
};
My query will only work if the query has the value of company id as well but i want to get company id how can i achive this. In my node js
dynamodb.getItem(optsq, function(err, compdata) {
if(err){
console.log(err);
}else{
console.log(compdata);
}
Instead of getItem, you should do a query, which allows you to specify only the userId.
var optsq = {
'ConsistentRead': true,
TableName : usertable,
KeyConditionExpression: "userid = :userid",
ExpressionAttributeValues: { ":userid": usrname },
ProjectionExpression: "companyid" }

How to stop the autoincrement for id in sails.js

//Controller
afterCreate: function(datas, cb) {
console.log("Data Id : ",datas.id);//Id:90150
var menudetails = { id : datas.id };//Id:90150
MenuDetail.create(menudetails).exec(function createMD(err, created){
console.log("MenuDetail",created);
console.log("MenuDetail Id : ",created.id);//Id:90103
if(err) return cb(err);
});
cb();
}
Here I'm trying to create the new record in MenuDetail with specific id, but it don't create the record for that specified id, it will generate the id which is autoincremented by previous id.
I need the record with specified id which is given as paramater.
An easy way to do this is to overwrite the id attribute on your model like so:
module.exports = {
attributes: {
id: {
type: 'integer',
autoIncrement: false,
unique: true,
primaryKey: true
}
}
}
Doing so will require you to set the id on each record you create.

Get last inserted id Sequelize

I'm using Sequelize and I'm trying to get the last inserted ID in raw query.
My query is
.query(Sequelize.Utils.format(["insert into MyTable (field1, field2) values (?,?)", val1, val2])
The query is done perfectly, but the result on success event is null.
Can someone help?
Thanks.
After some researches and zillions attempts, I understood how callee object work in sequelizeJs.
please, correct me if my answer is wrong.
the callee object needs this structure
{__factory:{autoIncrementField: 'parameterName'}, parameterName: '' }
in this case "parameterName" is the field that will store the new ID, sequelize looks for __factory.autoIncrementField to set value of last inserted id into property with its value (value of __factory.autoIncrementField).
so, my call to querys method would be
.query(sequelize.Utils.format(tempInsert), {__factory:{autoIncrementField: 'parameterName'}, parameterName: '' }, {raw: true})
this will result in object like that
{ __factory: { autoIncrementField: 'parameterName' }, parameterName: newInserted_ID }
thanks for all, and I hope this can help someone.
You have to add autoIncrement property in model definition.
const Article = sequelize.define('articles', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
}, {},
{
createdAt: false,
updatedAt: false
});
Then, you can access last inserted id with property in model definition.
Article.create(article)
.then(result => console.log(result.id));
Yes your answer is working. Another way would be
var Sequelize = require("sequelize")
var sequelize = new Sequelize('test', 'root', 'root', {dialect: 'mysql'})
var Page = sequelize.define( 'page', {
type : {type: Sequelize.STRING(20)},
order : {type: Sequelize.INTEGER, defaultValue: 1}
},{
timestamps: false,
underscored: true
})
Page.__factory = {autoIncrementField: 'id'}
Page.id = ''
sequelize.query('INSERT INTO pages SET `type` = ?, `order` = ?, `topic_version_id` = ?', Page, {raw: false}, ['TEXT', 1, 1] ).success(function(page) {
console.log(page)
Page.find(page.id)
.success(function(result){
console.log(result)
})
})
const addAuthUser = await authModel.create(
{
username: username,
password: hashedPassword
});
if (!addAuthUser) {
return next(new HttpError('SignUp Failed!', 401));
}
// this last inser id
console.log(addAuthUser.id)

Resources