我如何写帆function在控制器中使用?
我有一个关于帆的问题js:
- 如何在模型上编写帆function?在Controler中使用? 喜欢:
- beforeValidation / fn(values,cb)
- beforeCreate / fn(values,cb)
- afterCreate / fn(newInsertedRecord,cb)
如果您实际上正在尝试使用生命周期callback之一,则语法如下所示:
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(); } }
否则,您可以在模型上创build两种types的方法:
- 实例方法
- 收集方法
放置在属性对象中的方法将是“实例方法”(在模型的一个实例上可用)。 即:
// 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(); } } }
这将被用于这样的:
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` }); }
放置在属性对象之外但位于模型定义内的方法是“收集方法”,即:
// api/models/MyUsers.js module.exports = { attributes: { id: { type: 'string', primaryKey: true } }, myCollectionMethod: function (callback) { // 'this' keyword points to the 'MyUsers' collection callback(); } }
收集方法将会像这样使用:
MyUsers.myCollectionMethod(function (err, result) { if (err) { // handle error return; } // do something with `result` });
注意关于'this'这个关键字的意见是假设你以一种正常的方式使用这些方法,也就是说以我在例子中描述的方式来调用它们。 如果以不同的方式调用它们(即保存对方法的引用并通过引用调用该方法),则这些注释可能不准确。