Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda