Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify virtual fields from sequelize findAll result?

I have looked everywhere and couldn't find any clear answers for this. I have a complex findAll() with many inclusions and each with their own virtual fields. What I want is to modify the virtual fields of the result, however as it is returning the model instance trying to access the virtual fields returns undefined as they are not in the result yet. I have tried 'raw: true' but this removes all virtual fields and as my data has nested tables which also have their own virtual fields which I need, I cannot do that.

Example models

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');
    })

Getting the data

model.Book.findAll({
  limit: 100
})
.then((result) => {

  const newBook = result.map(row => {
    return {...row, myField: 'setMyOwnValueHere'}
  }

  return newBook
}
like image 673
Icecubelegacy Avatar asked Sep 07 '25 19:09

Icecubelegacy


1 Answers

Get model data first : get

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;
});
like image 183
mousto090 Avatar answered Sep 10 '25 08:09

mousto090