gpt4 book ai didi

javascript - node Sequelize如何写静态函数

转载 作者:搜寻专家 更新时间:2023-11-01 00:39:29 26 4
gpt4 key购买 nike

我有像 moongose 这样写静态函数的经验

    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 数据库使用了 sequelize

我的模型

 /*
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;
};

如何在这里添加静态函数..??

最佳答案

嗯,你可以很容易地使用 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(' '));
},
}
});

希望对您有所帮助。

关于javascript - node Sequelize如何写静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40019936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com