Home > Enterprise >  How to add new property in queried object - sequelize
How to add new property in queried object - sequelize

Time:03-31

I am using sequelize library in node project for relational database query.

getNotifications: async (req, res) => {
  const user = req.user

  try {
    const notifications = await user.getNotifications()

    res.status(200).send({
      notifications
    })

  } catch (error) {
    res.status(500).send({ message: error.message })
  }
}

The result is as follows

[
  {
    "id": 1,
    "user_id": 2,
    "body": "blablabla",
    "createdAt": "2022-03-30T00:19:13.000Z"
  }
]

But I want to add human readable value in each object like below

[
  {
    "id": 1,
    "user_id": 2,
    "body": "blablabla",
    "createdAt": "2022-03-30T00:19:13.000Z",
    "when": "1 minute ago"
  }
]

Let's assume that getting value when is no problem, the problem is how can I add attribute when without extra array function in controller? I would rather want something in model

Notification model is as follows

'use strict';
const {
  Model
} = require('sequelize');

module.exports = (sequelize, DataTypes) => {
  class Notification extends Model {
    static associate(models) {
      Notification.belongsTo(models.User, {
        as: 'user',
        foreignKey: 'user_id'
      })
    }
  }
  
  Notification.init({
    user_id: DataTypes.INTEGER,
    body: DataTypes.STRING,
    type: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'Notification',
  });
  return Notification;
};

CodePudding user response:

It seems you need to use virtual fields, see official documentation

Notification.init({
    user_id: DataTypes.INTEGER,
    body: DataTypes.STRING,
    type: DataTypes.STRING,
    when: {
      type: DataTypes.VIRTUAL,
      get() {
        return '1 minute ago';
      },
      set(value) {
        throw new Error('Do not try to set the `when` value!');
      }
  }

  }, {
    sequelize,
    modelName: 'Notification',
  })
  • Related