Sequelize afterFind挂钩未更改console.log中的数据



我试图在模型上运行afterFind钩子,但运行查询后,在带有JSON.stringify的console.log中,结果似乎没有改变。但是,如果我专门记录该属性,则数据会发生更改。

// on User model
User.hook('afterFind', function(result) {
result.teamCount = 1
return result.save()
}
})

然后当我尝试记录它时:

const result = await User.find()
console.log(result.teamCount) // -> 1
console.log(JSON.stringify(result)) // no "teamCount" attribute present

不确定钩子在做什么,或者是否需要save(),但似乎有什么问题,我如何在console.log中显示更改?

您应该将teamCount字段声明为virtual:

sequelize.define('user', {
...
teamCount: {
type: DataTypes.VIRTUAL
}
...
});

最新更新