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.
The following works for sequelize v4.
... const order = Order.findOne(criteria); order.setDataValue('additionalProperty', 'some value'); ...
Hope this helps. It's a bit late but in case people are still looking for answers.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With