如何在查询对象中添加新的 属性 - sequelize
How to add new property in queried object - sequelize
我在节点项目中使用sequelize库进行关系数据库查询。
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 })
}
}
结果如下
[
{
"id": 1,
"user_id": 2,
"body": "blablabla",
"createdAt": "2022-03-30T00:19:13.000Z"
}
]
但我想在每个对象中添加人类可读的值,如下所示
[
{
"id": 1,
"user_id": 2,
"body": "blablabla",
"createdAt": "2022-03-30T00:19:13.000Z",
"when": "1 minute ago"
}
]
假设获取值 when
没有问题,问题是如何在控制器中添加属性 when
而无需额外的数组函数?我宁愿想要模型中的东西
通知模型如下
'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;
};
您似乎需要使用 virtual
字段,请参阅 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',
})
我在节点项目中使用sequelize库进行关系数据库查询。
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 })
}
}
结果如下
[
{
"id": 1,
"user_id": 2,
"body": "blablabla",
"createdAt": "2022-03-30T00:19:13.000Z"
}
]
但我想在每个对象中添加人类可读的值,如下所示
[
{
"id": 1,
"user_id": 2,
"body": "blablabla",
"createdAt": "2022-03-30T00:19:13.000Z",
"when": "1 minute ago"
}
]
假设获取值 when
没有问题,问题是如何在控制器中添加属性 when
而无需额外的数组函数?我宁愿想要模型中的东西
通知模型如下
'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;
};
您似乎需要使用 virtual
字段,请参阅 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',
})