Home > Software design >  Why can't I use `user.roles = {...}` to add to a json string?
Why can't I use `user.roles = {...}` to add to a json string?

Time:09-10

I have the following model prototype (using Sequelize):

User.prototype.getUserWithRoles = async function () {
    let user = this;
    console.log(JSON.stringify(user));
    // prints {"id":288,"username":"test", ...}

    user.roles = {"Traveler": true};  //just for testing, I've set this as a static value
    console.log(JSON.stringify(user));
    // prints {"id":288,"username":"test", ...}

    ...

For the last line, I would have expected different output. I would have expected:

{
  "id":288,
  "username":"test", 
   ...,
   "roles": {
       "Traveler": true
   }
}

But the roles part is missing. What could be the cause of this? Is the format user.roles = {...} not valid?

CodePudding user response:

Queries in Sequelize don't return regular objects, but Model instance, to which you can't just add properties (well, you obviously can, but they won't show up when you stringify the object).

Instead, you have to define a virtual field, which are fields that look like they are a part of the Model instance, but won't actually be saved to the database:

roles: {
  type: DataTypes.VIRTUAL,
  get() {
    return { Traveler : true };
  }
}

Alternatively, if your goal is to return a regular object of a Model instance with a roles property added to it, you could use something like this (using Model inheritance):

class User extends Model {
  getUserWithRoles() {
    const obj = this.toJSON(); // convert to a regular Javascript object
    obj.roles = { Traveler : true };
    return obj;
  }
}
  • Related