2016-10-13 55 views
0

我有一個像節點Sequelize如何寫靜態函數

var mongoose =require('mongoose'); 
var Schema = mongoose.Schema; 
var adminSchema = new Schema({ 
    fullname : String, 
    number : Number, 
    email: String, 
    auth : { 
     username: String, 
     password : String, 
     salt: String 
    } 

}); 


adminSchema.statics.usernameInUse = function (username, callback) { 
    this.findOne({ 'auth.username' : username }, function (err, doc) { 
     if (err) callback(err); 
     else if (doc) callback(null, true); 
     else callback(null, false); 
    }); 
}; 

這裏usernameInUse在moongose書面靜功能體驗的功能是我瓦納寫的,但使用sequelize爲MySQL數據庫

我的模型

/* 
    This module is attendant_user table model. 
    It will store attendants accounts details. 
*/ 

"use strict"; 

module.exports = function(sequelize, DataTypes) { 
    var AttendantUser = sequelize.define('AttendantUser', { 

    username : { 
     type : DataTypes.STRING, 
     allowNull : false, 
     validate : { 
     isAlpha : true 
     } 
    },{ 
    freezeTableName : true, 
    paranoid : true 
    }); 

    return AttendantUser; 
}; 

如何在這裏添加靜態功能.. ??

回答

1
AttendantUser.usernameInUse = function (username, callback) { 
    ... 
}; 
return AttendantUser; 
+0

你可不可以只寫你嘗試過的代碼 –

0

那麼,你可以很容易地使用Expansion of models

var User = sequelize.define('user', { firstname: Sequelize.STRING }); 

// Adding a class level method 
User.classLevelMethod = function() { 
    return 'foo'; 
}; 

// Adding an instance level method 
User.prototype.instanceLevelMethod = function() { 
    return 'bar'; 
}; 

或在某些情況下,你可以使用getter和setter您的模型。見docs

A)定義爲屬性的一部分:

var Employee = sequelize.define('employee', { 
    name: { 
    type  : Sequelize.STRING, 
    allowNull: false, 
    get  : function() { 
     var title = this.getDataValue('title'); 
     // 'this' allows you to access attributes of the instance 
     return this.getDataValue('name') + ' (' + title + ')'; 
    }, 
    }, 
    title: { 
    type  : Sequelize.STRING, 
    allowNull: false, 
    set  : function(val) { 
     this.setDataValue('title', val.toUpperCase()); 
    } 
    } 
}); 

Employee 
    .create({ name: 'John Doe', title: 'senior engineer' }) 
    .then(function(employee) { 
    console.log(employee.get('name')); // John Doe (SENIOR ENGINEER) 
    console.log(employee.get('title')); // SENIOR ENGINEER 
    }) 

B)定義爲模型的一部分:

var Foo = sequelize.define('foo', { 
    firstname: Sequelize.STRING, 
    lastname: Sequelize.STRING 
}, { 
    getterMethods : { 
    fullName  : function() { return this.firstname + ' ' + this.lastname } 
    }, 

    setterMethods : { 
    fullName  : function(value) { 
     var names = value.split(' '); 

     this.setDataValue('firstname', names.slice(0, -1).join(' ')); 
     this.setDataValue('lastname', names.slice(-1).join(' ')); 
    }, 
    } 
}); 

希望它能幫助。