簡體   English   中英

節點續集如何編寫靜態函數

[英]node Sequelize how to write static functions

我有寫過像月球一樣的靜態函數的經驗

    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是我要編寫的函數,但對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;
};

如何在這里添加靜態函數。

好吧,您可以輕松使用模型擴展

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。 文檔

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(' '));
    },
  }
});

希望能幫助到你。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM