更新时间:2023-12-01 21:40:28
Sequelize 模型
类(你的猫是实例)有一个 toJSON()
方法,res.json可能会用来序列化你的猫。该方法返回 Model#get()
的结果( https://github.com/sequelize/sequelize/blob/95adb78a03c16ebdc1e62e80983d1d6a204eed80/lib/model.js#L3610-L3613 ),它只使用在模型。如果您希望能够在数据库中设置猫名称而不是商店名称,则可以在定义猫模型时使用虚拟列:
The Sequelize Model
class (of which your cats are instances) has a toJSON()
method which res.json will presumably use to serialise your cats. The method returns the result of Model#get()
(https://github.com/sequelize/sequelize/blob/95adb78a03c16ebdc1e62e80983d1d6a204eed80/lib/model.js#L3610-L3613), which only uses attributes defined on the model. If you want to be able to set the cats name, but not store names in the DB, you can use a virtual column when defining your cat model:
sequelize.define('Cat', {
// [other columns here...]
name: Sequelize.VIRTUAL
});
或者,如果您不想为模型定义添加属性:
Alternatively, if you don't want to add properties to the model definition:
cat = cat.toJSON(); // actually returns a plain object, not a JSON string
cat.name = 'Macavity';
res.json(cat);