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({w
It won't let me comment on the correct answer above (https://stackoverflow.com/a/38469390/562683), just wanted to add a use case where this helped me.
I have an existing mysql database that we cannot change the schema of (has to work with the old system and the new system until we can deprecate the old system) but we've layered MonogoDB as well for additional features until we can do a system refactor.
The answer above of the Virtual property helped because i'd basically make a placeholder for the mongo db information (in this case, an object activity log) and add it on the 'findMyObject' service call.
For example:
const model = sequelize.define('myobj', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
field: 'eventId',
},
name: { type: Sequelize.STRING, allowNull: false },
history: Sequelize.VIRTUAL,
...
}
Then in the MyObjectService, findMyObject call:
...
const result = yield MyObject.findOne(query);
result.history = yield getMyObjectHistoryArray(id);
return result;
And the resultant JSON looks like:
{
"id": 1,
"name": "My Name",
"history": [
{...},
{...},
]
}
So we were able to extend the object without changing the db, but still have an object in the backend where you can go:
let obj = yield findMyObject(id);
obj.name = "New Name";
return yield obj.save();
Which you wouldn't be able to do if, in the findMyObject function, you either did {raw: true} or result.get({plain: true})