nodejs使用Sequelize框架操作數(shù)據(jù)庫的實現(xiàn)
sequelize.define
使用該方法可以定義model,例子如下:
const Sequelize = require('sequelize');
var sequelize = new Sequelize(config.database, config.username, config.password, {
host: config.host,
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 30000
}
});
var Website = sequelize.define('website', {
id: {
type: Sequelize.BIGINT,
primaryKey: true,
autoIncrement: true
},
url: Sequelize.STRING(255),
title: Sequelize.STRING(255),
status: Sequelize.INTEGER,
delete_mark: Sequelize.BOOLEAN
}, {
timestamps: false
});
該方法傳入的第一個參數(shù)是數(shù)據(jù)表的單數(shù)形式,怎么理解呢?例如這里傳入的是website其實是模型名,數(shù)據(jù)表默認(rèn)是websites這樣的復(fù)數(shù)形式,這種約定我在Laravel中也碰見過,
也就是常說的,約定大于定義,也就是說,如果我們都按照約定的規(guī)范去開發(fā),那么效率其實比重新定義,要高很多。
那么,定義好了模型,該怎么進(jìn)行使用呢?
(async () => {
let demo = await Website.create({
url:'http://www.xxxx.com/',
title:'demo'
});
console.log(demo);
})();
繼承Model
const {Sequelize, DataTypes, Model} = require('sequelize');
const config = require('../config');
const sequelize = new Sequelize(config.database, config.username, config.password, {
host: config.host,
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 30000
}
});
/**
* @author chaojilaji
* 數(shù)據(jù)表websites的關(guān)系對象映射
*/
class WebSite extends Model {
}
WebSite.init({
id: {
type: Sequelize.BIGINT,
primaryKey: true,
autoIncrement: true
},
url: Sequelize.STRING(255),
title: Sequelize.STRING(255),
status: Sequelize.INTEGER,
delete_mark: Sequelize.BOOLEAN
}, {
sequelize,
modelName: 'Website',
timestamps:false
});
(async () => {
await sequelize.sync();
let x = await WebSite.create({
url: 'http://www.xxxxxxxx.com/',
title: 'demo2'
});
console.log(x);
})();
module.exports = WebSite;
我比較推薦使用繼承Model這種方式,通過創(chuàng)建一個class,這樣可以使用model.exports=模塊名的方式,將該模型封裝起來。供別的地方使用,只需要require進(jìn)去即可。
具體如何對數(shù)據(jù)表進(jìn)行操作,就比較簡單了,只需要參考API即可。 sequelize文檔地址
到此這篇關(guān)于nodejs使用Sequelize框架操作數(shù)據(jù)庫的實現(xiàn)的文章就介紹到這了,更多相關(guān)nodejs Sequelize操作數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Node.js?連接?MySql?統(tǒng)計組件屬性的使用情況解析
這篇文章主要為大家介紹了Node.js?連接?MySql?統(tǒng)計組件屬性的使用情況解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
node.js實現(xiàn)復(fù)制文本到剪切板的功能
這篇文章主要給大家介紹了node.js實現(xiàn)復(fù)制文本到剪切板的功能,文中介紹的非常詳細(xì),并給出示例代碼,相信對大家具有一定的參考借鑒價值,有需要的朋友們下面來一起看看吧。2017-01-01
nodeJS服務(wù)器的創(chuàng)建和重新啟動的實現(xiàn)方法
今天小編就為大家分享一篇nodeJS服務(wù)器的創(chuàng)建和重新啟動的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05

