Dynamically define and get Models in Waterline

て烟熏妆下的殇ゞ 提交于 2020-01-03 01:58:11

问题


I was wondering if it's possible in Waterline to define models or get a model by name like in Node-ORM2.

Defining:

var Person = db.define("person", {
    name      : String,
    surname   : String,
    age       : Number, // FLOAT
    male      : Boolean,
    continent : [ "Europe", "America", "Asia", "Africa", "Australia", "Antartica" ], // ENUM type
    photo     : Buffer, // BLOB/BINARY
    data      : Object // JSON encoded
}, {
    methods: {
        fullName: function () {
            return this.name + ' ' + this.surname;
        }
    },
    validations: {
        age: orm.enforce.ranges.number(18, undefined, "under-age")
    }
});

Getting:

var MyPersonModel = db.models["person"];

Thanks!


回答1:


Sails exposes your models on the sails.models object, so the following will work:

var MyPersonModel = sails.models['person'];

If you want to access your model off of the global object:

var MyPersonModel = global['Person'];

The sails object is also available as a property of the http request object, so in any route, you can do:

var MyPersonModel = req._sails.models['person'];

In fact, if you want to exclusively access models via sails.models or req._sails.models and you don't want sails to export your models as properties of the global object, you can set the configuration globals.models = false.

https://github.com/balderdashy/sails-generate-backend/blob/master/templates/config/globals.js#L53-62



来源:https://stackoverflow.com/questions/28747808/dynamically-define-and-get-models-in-waterline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!