1、定义model
形式如下:
module.export=(sequelize)=> {
class ModelName extends Model {
}
ModelName.init({}, {});
}
module.exports = (sequelize) => {
class User extends Model {
/**
* Create association between models
* @param models the database models
*/
static associate (models) {
User._models = models
User.hasMany(models.Opportunity, { foreignKey: 'ownerId', as: 'owners' })
User.hasMany(models.DiscussionPost, { foreignKey: 'authorId', as: 'posts' })
}
/**
* Get entity by id
* @param id the entity id
* @returns the User instance
*/
static async findById (id) {
const criteria = {
where: {
id
}
}
const entity = await User.findOne(criteria)
if (!entity) {
throw new errors.NotFoundError(`id: ${id} "User" doesn't exists.`)
}
return { id: entity.id, name: entity.name, profilePic: entity.profilePicture }
}
/**
* Get entity by name
* @param name the entity name
* @returns the User instance
*/
static async findByName (name) {
const criteria = {
where: {
name
}
}
const entity = await User.findOne(criteria)
if (!entity) {
throw new errors.NotFoundError(`name: ${name} "User" doesn't exists.`)
}
return { id: entity.id, name: entity.name, profilePic: entity.profilePicture }
}
/**
* Get entity by name
* @param oktaUsername the entity oktaUsername
* @returns the User instance
*/
static async findByOktaName (oktaUsername) {
const criteria = {
where: {
oktaUsername
}
}
const entity = await User.findOne(criteria)
if (!entity) {
throw new errors.NotFoundError(`oktaUsername: ${oktaUsername} "User" doesn't exists.`)
}
return { id: entity.id, name: entity.name, profilePic: entity.profilePicture }
}
}
User.init(
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false
},
name: {
type: Sequelize.STRING(128),
allowNull: false
},
profilePicture: {
field: 'profile_picture',
type: Sequelize.STRING(128),
allowNull: false
},
oktaUsername: {
field: 'okta_username',
type: Sequelize.STRING(45),
allowNull: false
}
},
{
schema: config.DB_SCHEMA_NAME,
sequelize,
timestamps: false,
tableName: 'user'
}
)
return User
}
2、管理多个Model
通过读取当前目录下的model文件,注册到模式管理器中
const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const config = require('config')
const basename = path.basename(module.filename)
const db = {}
const sequelize = new Sequelize(config.DB_DATABASE, config.DB_USERNAME, config.DB_PASSWORD, {
host: config.DB_HOST,
dialect: config.DB_DIALECT,
port: config.DB_PORT,
logging: config.DB_LOGGING
})
fs
.readdirSync(__dirname)
.filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'))
.forEach((file) => {
const model = require(path.join(__dirname, file))(sequelize)
db[model.name] = model
})
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db)
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db