如何从sequelize findAll结果中修改虚拟字段



我到处找了找,找不到任何明确的答案。我有一个复杂的findAll((,里面有很多包含项,每个包含项都有自己的虚拟字段。我想要的是修改结果的虚拟字段,然而,当它返回时,试图访问虚拟字段的模型实例返回未定义的结果,因为它们还不在结果中。我尝试过"raw:true",但这会删除所有虚拟字段,而且由于我的数据有嵌套的表,这些表也有我需要的自己的虚拟字段,所以我无法做到这一点。

示例模型

var Book = sequelize.define('Book', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
title: {
type: DataTypes.STRING
},
author: {
type: DataTypes.STRING
}
//....other columns,
myField: {
type: DataTypes.Virtual,
get() {
return this.getDataValue('title:') + this.getDataValue('author');
})

获取数据

model.Book.findAll({
limit: 100
})
.then((result) => {
const newBook = result.map(row => {
return {...row, myField: 'setMyOwnValueHere'}
}
return newBook
}

首先获取模型数据:获取

model.Book.findAll({
limit: 100
}).then(result => {
const books = result.map(row => {
//this returns all values of the instance, 
//also invoking virtual getters
const book = row.get();
book.myField = 'setMyOwnValueHere';
return book;
});
return books;
});

最新更新