Reputation: 175
I am trying to build a user, create a location (I'm using google geocode API) and save all, but the association isn't created in the database. Everything is working fine. The response is exactly what I want but when I go into the database, the association isn't created. The only way I made it work was to create and save the location entity separately and directly set the foreign key "locationId" to the newly generated ID. It's been almost a week and I still can't figure out how to make it work. If it can help, I'm also using PostgreSQL. Here is the doc for creation with associations.
Here are my associations:
User.belongsTo(models.Location, { as: 'location', foreignKey: 'locationId' });
Location.hasMany(models.User, { as: 'users', foreignKey: 'locationId' });
Here is my controller code:
const createRandomToken = crypto
.randomBytesAsync(16)
.then(buf => buf.toString('hex'));
const createUser = token => User.build({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
passwordResetToken: token,
passwordResetExpires: moment().add(1, 'days'),
role: req.body.roleId,
active: true
}, {
include: [{ model: Location, as: 'location' }]
});
const createLocation = (user) => {
if (!user) return;
if (!req.body.placeId) return user;
return googleMapsHelper.getLocationByPlaceId(req.body.placeId).then((location) => {
user.location = location;
return user;
});
};
const saveUser = (user) => {
if (!user) return;
return user.save()
.then(user => res.json(user.getPublicInfo()));
};
createRandomToken
.then(createUser)
.then(createLocation)
.then(saveUser)
.catch(Sequelize.ValidationError, (err) => {
for (let i = 0; i < err.errors.length; i++) {
if (err.errors[i].type === 'unique violation') {
return next(createError.Conflict(err.errors[i]));
}
}
})
.catch(err => next(createError.InternalServerError(err)));
Here's the response:
{
"id": 18,
"firstName": "FirstName",
"lastName": "LastName",
"email": "[email protected]",
"lastLogin": null,
"passwordResetExpires": "2018-04-15T21:02:34.624Z",
"location": {
"id": 5,
"placeId": "ChIJs0-pQ_FzhlQRi_OBm-qWkbs",
"streetNumber": null,
"route": null,
"city": "Vancouver",
"postalCode": null,
"country": "Canada",
"region": "British Columbia",
"formatted": "Vancouver, BC, Canada",
"createdAt": "2018-04-14T20:57:54.196Z",
"updatedAt": "2018-04-14T20:57:54.196Z"
}
Upvotes: 3
Views: 2202
Reputation: 175
After a couple back and forth with sequelize Github, I achieved to do the same thing using a transaction, the setters and modifying my promise logic.
const createLocation = new Promise((resolve, reject) => {
if (!req.body.placeId) return resolve();
googleMapsHelper
.getLocationByPlaceId(req.body.placeId)
.then(location => resolve(location))
.catch(() => reject(createError.BadRequest('PlaceId invalide')));
});
const createUser = () => sequelize.transaction((t) => {
const user = User.build({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
passwordResetToken: crypto.randomBytes(16).toString('hex'),
passwordResetExpires: moment().add(1, 'days'),
active: true
});
return user.save({ transaction: t })
.then(user => createLocation
.then(location => user.setLocation(location, { transaction: t })));
});
createUser
.then(user => res.json(user))
.catch(err => httpErrorHandler(err, next));
Upvotes: 1