Eggon
Eggon

Reputation: 2356

Sequelize: Virtual column is not returned in query results

I can't get this very simple virtual column to work (surnameName). It is not returned in query results, but it does not throw any error either.

My model (I removed irrelevant fields):

const Person = connectionPool.define('person', {
    ID: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true
    },
    name: Sequelize.STRING,
    surname: Sequelize.STRING,
    surnameName: {
        type: Sequelize.VIRTUAL(Sequelize.STRING, ['surname', 'name']),           
        get() {
            return this.getDataValue('surname') + ' ' + this.getDataValue('name');
        }
    }
});

This is how I query the model:

const cfg = {
    where: {},
    limit: 10,
    raw: false, // tried with and without this line
    attributes: ['surnameName']
}
models.Person.findAll(cfg)
.then(results => {
   console.log(results[0]);
})

And this is what I get in the console log:

person {
    dataValues: { surname: 'Baggins', name: 'Frodo' }, // all other fields are autoexcluded by Sequelize
    ...
    _options:
        { isNewRecord: false,
            _schema: null,
            _schemaDelimiter: '',
            raw: true,                    // is true even if I set 'raw' to false in findAll options
            attributes: [ 'surnameName', 'surname', 'name' ]   // <= surnameName is there!
        }
    }

Virtual column is not returned in the results, however the logged instance shows that the internal _options.attributes array does contain the field, so Sequelize somehow acknowledges that it should be added. I tried explicitly turning raw=false, as I read that raw excludes virtual columns, but it has no effect. The results are definitely not raw.

What can be wrong here? Any help will be appreciated!

Upvotes: 1

Views: 3977

Answers (1)

Ratul Sharker
Ratul Sharker

Reputation: 8011

It is possible to hide properties javascript object. Here is an example

function Person(fName, lName) {
  this.fName = fName;
  this.lName = lName;
  
  Object.defineProperties(this, {
      fullName: {
          get : function () {
              return this.fName + " " + this.lName; 
          }
      }
  });  
}

const ratul = new Person("Ratul", "sharker");

console.log(ratul);
console.log(ratul.fullName);

Look closely that console.log(ratul) does not print fullName, but fullName is sitting here, returning it's value seen in console.log(ratul.fullName).

Similar thing can be found in this answer.

Upvotes: 1

Related Questions