Git Product home page Git Product logo

Comments (5)

jspizziri avatar jspizziri commented on August 16, 2024

That's correct, as models are discovered and built on connect. Typically you would want to call connect when you app is initialized, like in app.js for instance. In the example code above, it is assumed that connect has already been called. I suppose I could make that a little clearer in the documentation.

The reason the behind this is that Models need to be defined in the context of a Sequelize instance (by calling sequelize.define()), which you cannot have without connecting.

Ex.

 var Model = sequelize.define("Model", {
    value:  DataTypes.INTEGER
  }, {
    underscored:  true,
    paranoid:     true,
    tableName:    'model',
    classMethods : {
      associate: function(models){
        Model.hasMany(models.OtherModel, { through: 'model_other_model'});
      }
    }
);

Effectively you don't have a model without having a sequelize instance.

Does that make sense? Or am I missing something.

from sequelize-singleton.

jspizziri avatar jspizziri commented on August 16, 2024

I've added a note to the documentation here: https://github.com/jspizziri/sequelize-singleton#configuring-sequelize-singleton

from sequelize-singleton.

shaoner avatar shaoner commented on August 16, 2024

Oh actually I was just confused because of the way Mongoose works.
I thought you meant to do this at the top of each file that needs a model

var User = models.User;

This would of course be a big constraint to ensure that your file is loaded only after the connection has been established.

I ended up writing a model wrapper which is completely agnostic to the Sequelize instance during its definition.

from sequelize-singleton.

jspizziri avatar jspizziri commented on August 16, 2024

If I'm not mistaken mongoose also needs to be"connected" upon app initialization.

Also, that's interesting, would you mind providing an example of the wrapper or at least an abstraction of its interface?

from sequelize-singleton.

shaoner avatar shaoner commented on August 16, 2024

No, mongoose doesn't need to be connected during the definition of the model. It only needs a connection when using the model, so you are able to require a model prior to mongoose connection:

var UserSchema = mongoose.Schema({ /* ... */ });
var User = mongoose.model('User', UserSchema);
/* 
 * Here nothing is connected yet and 
 * this is fine as long as I don't use User methods that need a connection
 * mongoose.model only register the schema for when the connection will be opened
*/
mongoose.connect(/* ... */);
/* Now I'm able to call User.find(...) */

About the wrapper, it's more like a schema wrapper actually so it's not that interesting it just allows me to retrieve all models from anywhere without taking care of require ordering, but just like orm.models in your example.

If you include orm.models everywhere it is fine to retrieve your models from there, it can be filled after the require statement.

Here is a simplified version of the schema wrapper:

'use strict';

var Sequelize = require('sequelize');
var _ = require('lodash');
var Schema = function (name, core, association, options) {
    if (!(this instanceof Model)){
        return new Model(name, core, association, options);
    }
    options = options || { };
    this._name = name;
    this._core = core;
    this._options = _.defaults(options, {
        /* my default options here */
        timestamps: false,
        underscored: true,
        underscoredAll: true,
        freezeTableName: true,
        classMethods: { },
        instanceMethods: { },
        hooks: { }
    });
    this._association = association;
};

Object.defineProperty(Schema.prototype, 'statics', {
    get: function () { return this._options.classMethods; }
});

Object.defineProperty(Schema.prototype, 'methods', {
    get: function () { return this._options.instanceMethods; }
});

Object.defineProperty(Schema.prototype, 'hooks', {
    get: function () { return this._options.hooks; }
});

Schema.Type = Sequelize;

So I am able to define my models like this:

'use strict';

var Schema = require('./schema');
var T = Schema.Type;
var $ = require('./models');

var User = Schema('User', {
    emailAddress: { type: T.STRING(255),  allowNull: false, unique: true },
    password: { type: T.STRING(255), allowNull: false },
    username: { type: T.STRING(50), unique: true },
}, function ($) {
    /* this is executed after all models have been loaded */
    this.hasOne($.Avatar);
});

User.statics.register = function (email, password) {
/* this.create(...) or $.User.create(...) */
};

User.methods.getProfile = function () {
    return { this.username };
};

module.exports = User;

$ variable is actually a map of models that is filled at startup, just like orm.models:

Db.prototype.load = function(schemaDir) {
    var self = this;
    var sequelize = this.sequelize;
    var schema;
    fs.readdirSync(schemaDir).forEach(function(name) {
        schema = require(path.join(schemaDir, name));
        if (schema instanceof Schema) {
            // Create the sequelize model and store it in $
            $[schema._name] = sequelize.define(schema._name,
                                              schema._core,
                                              schema._options);
            self.schemas.push(schema);
        }
    });
    // Add associations
    this.schemas.forEach(function (schema) {
        if (_.isFunction(schema._association)) {
            schema._association.apply($[schema._name], [ $ ]);
        }
    });
};

So now, I'm able to retrieve models the same way using:

var $ = require('./models');
/* Here it may be empty */

router.get('/', function (req, res) {
   /* 
    * Here I'm sure $ contains all models
    * because I made it a requirement for the application to start 
   */
   $.User.find(/* ... *).then(/*... */);
});

To make it just like mongoose, we could imagine setting a sequelize attribute to the Schema wrapper after the connection has been established, and binding the sequelize methods to it as well:

Object.defineProperty(Schema.prototype, 'find', {
    get: function () {
     if (!this._seqmodel) { throw new Error('connection is not opened yet'); }
     return this._seqmodel.find;
});

User would be an instance of Schema or Model bound to a sequelize model under the hood, so you would only be able to use these methods after the connection has been established.

from sequelize-singleton.

Related Issues (6)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.