-
Notifications
You must be signed in to change notification settings - Fork 0
Models
Models are classes used to structure data into a single schema paradigm.
Models are defined in /api/models/
as [name]_model.js
. Example: /api/models/user_model.js
., for example, a sample user model:
module.exports = {
name: {
required: true,
type: "string"
},
email: {
required: true,
type: "email"
},
password: {
required: true,
type: "password"
},
}
All attributes should be defined in the model file as described below:
password: {
// default: false
required: true,
// attribute type defined which
// validator should handle its input
type: "password"
},
Then, you can create a new model instance using the method Model.create
as shown below:
var user = model.create("user", {
name: "name",
email: "[email protected]",
password: "abcd1234",
access_token: "01234567890"
});
console.log(user.email); // prints: "[email protected]"
The validation is provided by the Types Class, in the Model Adapater and is a framework important class, don't change it unless you're really sure what you're doing.
Available Types:
- string
- int
- numeric (float)
- string
- password (at least 8 characters length)
- Check if it has at least 8 characters length
- Available Encryption Methods:
- md5
- sha1
- sha256
- sha512
- Some other OpenSSL encryption algorithms. Checkout NodeJS Crypto for more details.
- object (obs: only in non-relational databases)
- array (obs: only in non-relational databases)
You can store a model instance in the database using the method Model.save
.
var user = model.create("user", {
name: "name",
email: "[email protected]",
password: "abcd1234",
access_token: "01234567890"
});
Model.save(user);
OBS: This method also encapsulates the item update in database, so there's no Model.update
method, you call Model.save
and it will query the item _id
attribute in the database and decide if it should be created or updated.
To get a previously saved model from the database you have to call the method Model.find
, as shown below:
Model.find("user", {email: "[email protected]"}, function(items){
var user = items[0];
console.log(user.email); // prints: "[email protected]"
}
create
- Params:
- Model Name (String)
- Input (Object)
- Return:
- Model instance
save
- Params:
- Model Instance (Object)
- Callback (Function)
- Params: result [true/false]
- Return:
- Model instance