问题
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