Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get opt.model.name undefined #1

Closed
jusefb opened this issue Jul 17, 2016 · 10 comments
Closed

Get opt.model.name undefined #1

jusefb opened this issue Jul 17, 2016 · 10 comments
Labels

Comments

@jusefb
Copy link

jusefb commented Jul 17, 2016

Hi,

I have tried to use the library but unfortunately I am getting an error at the step when the revision gets built. It seem that opt.model.name property is undefined in my case. Is there a specific format in which the model has to be constructed for this to work? Here is the portion of code that throws the error [TypeError: Cannot read property 'name' of undefined] in lib.js line 272

  // Build revision
  var revision = Revision.build({
    model: opt.model.name,
    document_id: instance.get("id"),
    // TODO: Hacky, but necessary to get immutable current representation
    document: currentVersion
  });

Thank you in advance for you help

@nielsgl
Copy link
Owner

nielsgl commented Jul 17, 2016

Hi @jusefb thanks for the feedback. Did you enable the paper trail for that model? For example, if you have a user model, it should be enabled like this:

'use strict';
module.exports = function(sequelize, DataTypes) {
  var user = sequelize.define('User', {
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    }
  }, {
    classMethods: {
      associate: function(models) {
        // other associations can be defined here
      }
    }
  });

  user.hasPaperTrail();

  return user;
};

@jusefb
Copy link
Author

jusefb commented Jul 19, 2016

Apologies for a late response. Yes I have enabled paper trail for the model in question. I was trying to understand where the opt.model.name is set but could not find it.

@nielsgl
Copy link
Owner

nielsgl commented Jul 20, 2016

When the before and after hooks are added, sequelize automatically sets the right values for instance and opt when the hooks are triggered, so it happens internally.
See http://docs.sequelizejs.com/en/latest/docs/hooks/#sequelizeaddhook-permanent-hook
Can you set debug to true in the options and share the debug statements here, that should tell some more about the object and the model options. This line will print the model.opt values when the after hook is called: https://github.com/nielsgl/sequelize-paper-trail/blob/master/lib/index.js#L241 so look for the opt details after this 'afterHook called' is printed to the console. Also which database are you using?

@jusefb
Copy link
Author

jusefb commented Jul 22, 2016

Here is the debug output:

afterHook called
instance: { dataValues:
{ revision: 1,
id: 15,
hospitalisation_id: 7,
treatment_type_id: 1,
operation_mode_id: 1,
oxygen_flow: 1,
start_date: null,
end_date: null,
stop_date: null,
updated_at: Fri Jul 22 2016 23:40:47 GMT+0100 (BST),
created_at: Fri Jul 22 2016 23:40:47 GMT+0100 (BST),
title: null,
duration: null,
status: null,
machine_type_id: null,
user_id: null,
bill_id: null,
billed_item_id: null },
_previousDataValues:
{ hospitalisation_id: undefined,
treatment_type_id: undefined,
operation_mode_id: undefined,
oxygen_flow: undefined,
start_date: undefined,
end_date: undefined,
stop_date: undefined,
revision: undefined },
_changed:
{ hospitalisation_id: true,
treatment_type_id: true,
operation_mode_id: true,
oxygen_flow: true,
start_date: true,
end_date: true,
stop_date: true,
revision: true },
'$modelOptions':
{ timestamps: true,
instanceMethods: {},
classMethods: { associate: [Function] },
validate: {},
freezeTableName: false,
underscored: true,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: { id: '6' },
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks:
{ beforeCreate: [Object],
beforeUpdate: [Object],
afterCreate: [Object],
afterUpdate: [Object] },
indexes: [],
name: { plural: 'Treatments', singular: 'Treatment' },
omitNul: false,
sequelize:
{ options: [Object],
config: [Object],
dialect: [Object],
models: [Object],
modelManager: [Object],
connectionManager: [Object],
importCache: [Object],
test: [Object],
queryInterface: [Object] },
uniqueKeys: {},
hasPrimaryKeys: true },
'$options':
{ isNewRecord: true,
'$schema': null,
'$schemaDelimiter': '',
attributes: undefined,
include: undefined,
raw: undefined,
silent: undefined },
hasPrimaryKeys: true,
__eagerlyLoadedAssociations: [],
isNewRecord: false,
context: { delta: [ [Object], [Object], [Object], [Object], [Object] ] } }
opt: { hooks: true,
validate: true,
fields:
[ 'id',
'title',
'start_date',
'end_date',
'stop_date',
'oxygen_flow',
'duration',
'status',
'created_at',
'updated_at',
'revision',
'hospitalisation_id',
'machine_type_id',
'operation_mode_id',
'user_id',
'treatment_type_id',
'bill_id',
'billed_item_id' ],
defaultFields:
[ 'id',
'title',
'start_date',
'end_date',
'stop_date',
'oxygen_flow',
'duration',
'status',
'created_at',
'updated_at',
'revision',
'hospitalisation_id',
'machine_type_id',
'operation_mode_id',
'user_id',
'treatment_type_id',
'bill_id',
'billed_item_id' ],
returning: true }

@nielsgl
Copy link
Owner

nielsgl commented Jul 23, 2016

Thanks, that's really helpful :) It looks like opt.model.name is undefined because you explicitly specify the name with the singular and plural names. From the logs it looks like you have this in your model specification

name: { plural: 'Treatments', singular: 'Treatment' }

Is there a reason for doings this? Sequelize should be able to handle it by itself.
I'm going to try to replicate this situation and work on a fix this weekend.

@nielsgl nielsgl added the bug label Jul 23, 2016
@jusefb
Copy link
Author

jusefb commented Jul 24, 2016

In my application I load the models automatically from the model directory (this was based on a sequelize example)

fs
      .readdirSync(__dirname)
      .filter(function (file) {
        return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
      })
      .forEach(function (file) {
        var model = sequelize['import'](path.join(__dirname, file));

        db[model.name] = model;
      });

  Object.keys(db).forEach(function (modelName) {
    if (db[modelName].associate) {
      db[modelName].associate(db);
    }
  });

So I am not sure what sets the plural and singular names. I assume it is the sequilize import function. Is there a workaround I could use you think?

@nielsgl
Copy link
Owner

nielsgl commented Jul 24, 2016

If you want a really quick (and a dirty) fix for it you can do this:
In lib.js, on line 272 where the error is thrown, replace opt.model.name with:

instance['$modelOptions'].name.singular

that should resolve it in your case I think while I look into a better solution today. Let me know if that works!

@nielsgl
Copy link
Owner

nielsgl commented Sep 29, 2016

Will close this for now, please reopen it if it is still an issue.

@nielsgl nielsgl closed this as completed Sep 29, 2016
@eric-radiant
Copy link

I had/have the same issue, using the same example sequelize code to load in different model files.

@eric-radiant
Copy link

seems like it would be easy enough for the official code to check if instance['$modelOptions'].name.singular or opt.model.name is what is available.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants