我可以在Sequelize中将属性的getter定义为asyc函数吗?
在 getter 中,我应该从另一个表中检索一个值,我已经在模型定义中尝试过:
...
bio: {
type: Sequelize.STRING,
get: async function() {
let bio = this.getDataValue('bio');
if (bio) {
let bestFriend = await db.models.User.findById(this.getDataValue('BestFriendId'))
if(bestFriend){
bio += ` Best friend: ${bestFriend.name}.`;
}
console.log(bio)
return bio;
} else {
return '';
}
}
},
...
日志记录我可以阅读正确的简历,如下所示:Born yesterday. Love to read Best friend: Markus
但是我检索的对象在 bio 属性中有一个空对象。
我想这是因为不支持异步功能,我错了吗?
如何在不使用异步函数的情况下实现此目的?
根据文档,getter 和 setter 不支持任何形式的异步。它们是同步的。所以没有办法使用异步函数(因为我们需要承诺支持(。
这里还有一个关于这个主题的讨论。并且已确认将来不会添加此功能。
您可以改为扩展模型并添加实例级别方法。文档称其为virtual getter
。请参阅此文章。
您还可以使其async
并访问模型数据。
BioModel.prototype.getBio = async function() {
let bio = this.getDataValue('bio');
if (bio) {
let bestFriend = await db.models.User.findById(this.getDataValue('BestFriendId'))
if(bestFriend){
bio += ` Best friend: ${bestFriend.name}.`;
}
return bio;
} else {
return '';
}
}
在 Sequelize 中,您可以定义延迟虚拟字段,即从代码中的策略位置写入和读取,而不是从模型架构中写入和读取。如果您将虚拟值与持久值一起存储,则它们由model.get()
、model.toJSON()
、
设置
myVirtualField: {
type: new DataTypes.VIRTUAL(DataTypes.STRING),
get() {
return this.getDataValue("myVirtualField")
},
set(value) {
this.setDataValue("myVirtualField", value)
},
},
用法
// before writing anything into myVirtualField, `item.getDataValues()` has no entry for it
if (item.myVirtualField === undefined) { // <- true
// set myVirtualField
item.myVirtualField = await getHelloWorldAsync() // this resolves to "Hello, World!"
// after writing anything into myVirtualField, `item.getDataValues()` has an entry for it
if (item.myVirtualField === "Hello, World!") { // <- true