Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
How to add new property in queried object - sequelize

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;
};
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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',
  })
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda