gpt4 book ai didi

node.js - 建立并保存关联

转载 作者:行者123 更新时间:2023-12-02 02:55:13 25 4
gpt4 key购买 nike

我正在尝试建立一个用户,创建一个位置(我使用的是谷歌地理编码 API)并保存所有内容,但该关联并未在数据库中创建。一切正常。响应正是我想要的,但是当我进入数据库时​​,没有创建关联。我让它工作的唯一方法是单独创建和保存位置实体,并将外键“locationId”直接设置为新生成的 ID。已经将近一个星期了,我仍然不知道如何让它发挥作用。如果有帮助,我也在使用 PostgreSQL。这是 creation with associations. 的文档

这是我的联想:

User.belongsTo(models.Location, { as: 'location', foreignKey: 'locationId' });
Location.hasMany(models.User, { as: 'users', foreignKey: 'locationId' });

这是我的 Controller 代码:

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)));

这是响应:

{
"id": 18,
"firstName": "FirstName",
"lastName": "LastName",
"email": "test@test.com",
"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"
}

最佳答案

在与 sequelize Github 来回交流之后,我实现了使用事务、setter 和修改我的 promise 逻辑来做同样的事情。

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));

关于node.js - 建立并保存关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49836363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com