【发布时间】:2019-05-06 12:32:11
【问题描述】:
我有 2 个模型,patient 和 personalInformation。
有一个关联,例如personalInformation.belongsTo(patient)。在我的例子中,patient 主键或 uuid 作为 personalInformation 表中的一列存在。
当我的 API 收到一个 POST 请求时,我打算让我的控制器一起创建一个 patient 条目和 personalInformation 条目。
这是我的控制器代码:
// patient.controller.js
const db = require('../../db/databaseConfig');
const Patient = db.patients;
const PersonalInformation = db.personalInformation;
PersonalInformation.Patient = PersonalInformation.belongsTo(Patient);
exports.create = async (req, res) => {
try {
let payload = await req.body;
await console.log('Recevied request: CREATE /api/patients & payload: ', payload);
let newPatientEntry = Patient.create();
let newPInfo = await PersonalInformation.create({
...payload,
patient: newPatientEntry
}, {
include: [{
association: PersonalInformation.Patient,
}]
});
res.send(newPInfo);
} catch (e) {
console.log('error inside create method Patient controller');
throw new Error(e);
}
};
结果是 2x 患者条目和 1x 个人信息条目,而不是 1x 患者条目和 1x 个人信息条目。个人信息条目在表中有一个患者的 uuid(创建的 2 个患者中的后者)。我不知道为什么有两个患者条目。
这里是相关的nodejs日志:
2018-12-05T01:17:57.644499+00:00 app[web.1]: Executing (default): INSERT INTO "patients" ("uuid","createdAt","updatedAt") VALUES ('89290b66-999d-4f10-96b3-4105a26a9450','2018-12-05 01:17:57.583 +00:00','2018-12-05 01:17:57.583 +00:00') RETURNING *;
2018-12-05T01:17:57.645703+00:00 app[web.1]: Executing (default): INSERT INTO "patients" ("uuid","createdAt","updatedAt") VALUES ('9ed075da-757a-457b-b939-ed7e4c7b523a','2018-12-05 01:17:57.612 +00:00','2018-12-05 01:17:57.612 +00:00') RETURNING *;
2018-12-05T01:17:57.659918+00:00 app[web.1]: Executing (default): INSERT INTO "personalInformations" ("id","nameTitle","nameFirst","nameMiddle","nameLast","nameSuffix","nameAlias","dateOfBirth","sex","gender","occupation","deceased","createdAt","updatedAt","patientUuid") VALUES (DEFAULT,'Mr','Robert','Swan','Mueller','II','Bob','1950-12-15 00:00:00.000 +00:00','Male','Man','Special Counsel','False','2018-12-05 01:17:57.594 +00:00','2018-12-05 01:17:57.594 +00:00','9ed075da-757a-457b-b939-ed7e4c7b523a') RETURNING *;
模型结构如下:
// patient.model.js
const uuid = require('uuid/v4');
module.exports = (sequelize, Sequelize) => {
const Patient = sequelize.define('patient', {
uuid: {
primaryKey: true,
allowNull: false,
type: Sequelize.UUID,
defaultValue: () => uuid(),
}
});
return Patient;
};
和
// personalInformation.model.js
module.exports = (sequelize, Sequelize) => {
const PersonalInformation = sequelize.define('personalInformation', {
nameFirst: {
type: Sequelize.STRING,
notEmpty: true,
allowNull: false,
},
nameLast: {
type: Sequelize.STRING,
notEmpty: true,
allowNull: false,
},
... etc
... etc
});
return PersonalInformation;
}
【问题讨论】:
标签: javascript node.js database postgresql sequelize.js