将属性添加到Sequelize FindOne返回的对象 [英] Add Property to Object that is returned by Sequelize FindOne

查看:1078
本文介绍了将属性添加到Sequelize FindOne返回的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在将sequelize实例传递回客户端之前将其添加到sequelize实例中。

I am trying to add a property to a sequelize instance before passing it back to the client.

router.get('/cats/1', function (req, res) {
    Cat.findOne({where: {id: 1}})
        .then(function (cat) {
            // cat exists and looks like {id: 1}
            cat.name = "Lincoln";
            // console.log of cat is {id: 1, name: Lincoln}
            res.json(cat);
        });
});

客户只看到 {id:1} 而不是新添加的密钥。

The client only see's {id: 1} and not the newly added key.


  • 这里发生了什么?

  • Sequelize返回什么类型的Object?

  • 如何向我的猫添加新属性并将其发回?

推荐答案

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);

这篇关于将属性添加到Sequelize FindOne返回的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆