将属性添加到 Sequelize FindOne 返回的对象

Add Property to Object that is returned by Sequelize FindOne(将属性添加到 Sequelize FindOne 返回的对象)
本文介绍了将属性添加到 Sequelize FindOne 返回的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  • What is going on here?
  • What type of Object is returned by Sequelize?
  • How can I add new properties to my Cats and send them back?

解决方案

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 返回的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)