Reputation: 33
I have a question on sails js:
Upvotes: 1
Views: 2493
Reputation: 2289
If you are actually trying to use one of the lifecycle callbacks, the syntax would look something like this:
var uuid = require('uuid');
// api/models/MyUsers.js
module.exports = {
attributes: {
id: {
type: 'string',
primaryKey: true
}
},
beforeCreate: function(values, callback) {
// 'this' keyword points to the 'MyUsers' collection
// you can modify values that are saved to the database here
values.id = uuid.v4();
callback();
}
}
Otherwise, there are two types of methods you can create on a model:
Methods placed inside the attributes object will be "instance methods" (available on an instance of the model). i.e.:
// api/models/MyUsers.js
module.exports = {
attributes: {
id: {
type: 'string',
primaryKey: true
},
myInstanceMethod: function (callback) {
// 'this' keyword points to the instance of the model
callback();
}
}
}
this would be used as such:
MyUsers.findOneById(someId).exec(function (err, myUser) {
if (err) {
// handle error
return;
}
myUser.myInstanceMethod(function (err, result) {
if (err) {
// handle error
return;
}
// do something with `result`
});
}
Methods placed outside the attributes object but inside the model definition are "collection methods", i.e.:
// api/models/MyUsers.js
module.exports = {
attributes: {
id: {
type: 'string',
primaryKey: true
}
},
myCollectionMethod: function (callback) {
// 'this' keyword points to the 'MyUsers' collection
callback();
}
}
the collection method would be used like this:
MyUsers.myCollectionMethod(function (err, result) {
if (err) {
// handle error
return;
}
// do something with `result`
});
P.S. the comments about what the 'this' keyword will be are assuming that you use the methods in a normal way, i.e. calling them in the way that I described in my examples. If you call them in a different way (i.e. saving a reference to the method and calling the method via the reference), those comments may not be accurate.
Upvotes: 8