Estoy usando la biblioteca de secuencias en el proyecto de nodo para la consulta de la base de datos relacional.
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 }) } }El resultado es el siguiente
[ { "id": 1, "user_id": 2, "body": "blablabla", "createdAt": "2022-03-30T00:19:13.000Z" } ]Pero quiero agregar valor legible por humanos en cada objeto como a continuación
[ { "id": 1, "user_id": 2, "body": "blablabla", "createdAt": "2022-03-30T00:19:13.000Z", "when": "1 minute ago" } ] Supongamos que obtener valor when no es un problema, el problema es ¿cómo puedo agregar un atributo when no tengo una función de matriz adicional en el controlador? Prefiero querer algo en modelo.
El modelo de notificación es el siguiente
'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; };Parece que necesita usar campos virtual , consulte la documentación oficial
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', })