简体   繁体   中英

Set default value to a model(Sails.js)

I am starting to learn Sails.js and I want to know if there is a simpler way to set the default value in a model from a session variable? I am using Waterlock to do authentication and setting the user_id in a session variable like req.session.user_id . I have a message model, I want to default the 'from' field to this session variable. Is there a way to do this in Sails.js?

If you are using Sail's default ORM, Waterline , then model attributes have a defaultsTo option. The supplied value may be a function. You can look at the waterline documentation .

Sample Model

module.exports = {
  attributes: {
    description: {
      type: 'string',
      defaultsTo: 'No description.'
    },
    email: {
      type: 'email',
      required: true,
      unique: true
    },
    alias: {
      type: 'string',
      defaultsTo: function(){
        return this.email;
      }
    },
  }
};

If the supplied value is a function, then the call to this function is bound to the values in the create.

For Model.create(values)... , if alias is null/undefined, then alias = defaultsTo.call(values) is used to get the value for alias.

So to use req.session.user_id you may have to include it during create. Model.create({session: req.session,...}) . I am not really sure, since I do not use Waterlock. And I'm not don't think this is the best way to go about it.

From my experience these extra values are ignored when using adapters such as sails-mysql , but if you are using sails-disk for development, then you might see that these extra values are persisted. You may want to delete them before you persist.

  beforeCreate: function(values, cb){
    delete values['session'];
    cb();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM