I got some problems with Sequelize and promise (mainly with promise). Example : I want all my Events and the master of this events. I've done something like that :
models.events.findAll().then(function(event) {
events.forEach(function(event){
events.dataValues.master = event.getUsers({
where: ['UserRelationEvent.relation = "master"'],
joinTableAttributes: []
}).then(function(user){
return user[0].dataValues;
});
});
return next(events);
}).catch(function(err) {next(err)});
But there I got an Sequelize Object.. I checked my content of user[0].dataValues
It's exactly what I want.. so I think I miss something and misunderstood something with promises :/
I try many things but mainly my question is : how can I retrieve my string from my console.log
I got some problems with Sequelize and promise (mainly with promise). Example : I want all my Events and the master of this events. I've done something like that :
models.events.findAll().then(function(event) {
events.forEach(function(event){
events.dataValues.master = event.getUsers({
where: ['UserRelationEvent.relation = "master"'],
joinTableAttributes: []
}).then(function(user){
return user[0].dataValues;
});
});
return next(events);
}).catch(function(err) {next(err)});
But there I got an Sequelize Object.. I checked my content of user[0].dataValues
It's exactly what I want.. so I think I miss something and misunderstood something with promises :/
I try many things but mainly my question is : how can I retrieve my string from my console.log
1 Answer
Reset to default 7event.getUsers
returns a promise - so you are assigning events.dataValues.master
(which is the array, not the particular event btw) the promise, not the value.
Also, you are returning next
, before getUsers
is done, because they happen async
Something like this should work
models.events.findAll().then(function(events) {
sequelize.Promise.each(events, function(event){
return event.getUsers({
through: {
where: { relation: 'master' }
},
joinTableAttributes: []
}).then(function(user){
event.dataValues.master = user[0];
});
}).then(function (events) {
return next(events);
});
}).catch(function(err) {next(err);});
When you return a promise to the callback in promise.each, the then
(which calls next
) is not invoked, before all the returned promises are done (i.e. before all getUsers
calls are done.
I've also changed the where clause to use an object instead of string :)
But wait! We can do better!
models.events.findAll({
include: [
{
model: User,
through: {
where: {
relation: 'master'
}
}
}
]
}).then(function(events) {
return next(events);
}).catch(function(err) {next(err);});
This left joins the users table where the relation is master. You may want to do a map in the then
, because users will be placed under .users
, not .master