How to create a normal sails model without being in the models folder

前端 未结 5 1032
春和景丽
春和景丽 2021-02-13 05:50

So,

I\'m in the middle of implementing a plugin api for my application, and the plugins can have their own models, imagine this.

SimplePlugin = {
    pl         


        
5条回答
  •  南旧
    南旧 (楼主)
    2021-02-13 06:24

    EDIT: not working completely since collections are assigned to connections at initialization.

    Seems that there is a better solution, with 3 lines of code and without disconnecting/reconnecting databases. I just studied the source code of Waterline (see https://github.com/balderdashy/waterline/blob/master/lib/waterline.js#L109). It's possible to do something like:

    var Waterline = require('waterline');
    
    // Other dependencies
    var Schema = require('waterline-schema');
    var CollectionLoader = require('waterline/lib/waterline/collection/loader');
    
    var orm = new Waterline();
    
    var config = {
        // Setup Adapters
        // Creates named adapters that have have been required
        adapters: {
            'default': 'mongo',
            mongo: require('sails-mongo')
        },
    
        // Build Connections Config
        // Setup connections using the named adapter configs
        connections: {
            'default': {
                adapter: 'mongo',
                url: 'mongodb://localhost:27017/sausage'
            }
        }
    };
    
    orm.initialize(config, function(err, data) {
        if (err) {
            throw err;
        }
    
        // ORM initialized, let's add another model dynamically
        var User = Waterline.Collection.extend({
           identity: 'user',
            connection: 'default',
    
            attributes: {
                first_name: 'string',
                last_name: 'string'
            }
        });
        orm.loadCollection(User);
    
        var defaults = config.defaults || {};
    
        // This is where the magic happens
        var loader = new CollectionLoader(User, orm.connections, defaults);
        var collection = loader.initialize(orm);
        orm.collections[collection.identity.toLowerCase()] = collection;
    
        // Done! You can now use orm.collections.user :-D
    });
    

提交回复
热议问题