我收到此错误:
AggregateError: aggregate error
at Promise.try.then
...
当尝试使用此代码依次设置多对多表时:
let _document
db.document.create(payload, { include: ['documentAttributes', 'documentChildren'] })
.then(document => {
_document = document
const promises = []
// Add tags if there are any
if (req.body.tags) {
req.body.tags.forEach(tag => {
promises.push(db.tag.findOrCreate({ where: { key: tag.key } }))
})
}
return Promise.all(promises)
})
.then(tags => {
if (tags.length > 0) {
const allTags = tags.map(tag => tag[0])
return _document.setTags(allTags) // THIS LINE CAUSES THE ISSUE
}
document.js
模型:
'use strict'
module.exports = (sequelize, DataTypes) => {
const document = sequelize.define('document', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
...
lastUpdatedBy: {
allowNull: false,
type: DataTypes.UUID
}
},
{
updatedAt: 'lastUpdatedAt'
})
document.associate = function (models) {
document.hasMany(models.documentAttribute)
document.hasMany(models.documentChildren)
document.belongsToMany(models.tag, { through: 'documentTags' })
}
return document
}
tag.js
模型:
'use strict'
module.exports = (sequelize, DataTypes) => {
const tag = sequelize.define('tag', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
key: {
allowNull: false,
type: DataTypes.STRING
},
value: {
allowNull: false,
type: DataTypes.STRING
},
lastUpdatedBy: {
allowNull: false,
type: DataTypes.UUID
}
},
{
updatedAt: 'lastUpdatedAt'
})
tag.associate = function (models) {
tag.belongsToMany(models.document, { through: 'documentTags' })
}
return tag
}
documenttags.js
模型:
'use strict'
module.exports = (sequelize, DataTypes) => {
const documentTags = sequelize.define('documentTags', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
documentId: {
allowNull: false,
type: DataTypes.UUID
},
tagId: {
allowNull: false,
type: DataTypes.UUID
},
lastUpdatedBy: {
allowNull: false,
type: DataTypes.UUID
}
},
{
updatedAt: 'lastUpdatedAt'
})
documentTags.associate = function (models) {
// associations can be defined here
}
return documentTags
}
答案 0 :(得分:1)
查看文档并在聊天中讨论之后。 through
属性对于在多对多表上设置额外的属性是必需的。
http://docs.sequelizejs.com/class/lib/associations/belongs-to-many.js~BelongsToMany.html
return _document.setTags(allTags, { through: { lastUpdatedBy: tag.lastUpdatedBy }})