Node.js 使用关联生成和保存
我正在尝试构建一个用户,创建一个位置(我正在使用谷歌地理编码API)并保存所有内容,但数据库中没有创建关联。一切正常。响应正是我想要的,但是当我进入数据库时,关联没有被创建。唯一可行的方法是单独创建和保存位置实体,并直接将外键“locationId”设置为新生成的ID。已经快一个星期了,我仍然不知道如何使其工作。如果可以的话,我也在使用PostgreSQL。这是你的医生 以下是我的联想:Node.js 使用关联生成和保存,node.js,sequelize.js,Node.js,Sequelize.js,我正在尝试构建一个用户,创建一个位置(我正在使用谷歌地理编码API)并保存所有内容,但数据库中没有创建关联。一切正常。响应正是我想要的,但是当我进入数据库时,关联没有被创建。唯一可行的方法是单独创建和保存位置实体,并直接将外键“locationId”设置为新生成的ID。已经快一个星期了,我仍然不知道如何使其工作。如果可以的话,我也在使用PostgreSQL。这是你的医生 以下是我的联想: User.belongsTo(models.Location, { as: 'location', fore
User.belongsTo(models.Location, { as: 'location', foreignKey: 'locationId' });
Location.hasMany(models.User, { as: 'users', foreignKey: 'locationId' });
这是我的控制器代码:
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)));
在使用sequelize Github来回几次之后,我实现了使用事务、setters和修改承诺逻辑来做同样的事情
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));
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));