1.在根目錄下建立models和database文件夾热凹,model內(nèi)創(chuàng)建note.js,用于數(shù)據(jù)庫的模型,database用于存放數(shù)據(jù)庫
var Sequelize = require('sequelize');
var path = require('path')
var sequelize = new Sequelize(undefined, undefined, undefined, {
host: 'localhost',
dialect: 'sqlite',
storage: path.join(__dirname,'../database/database.sqlite')
});
var Note = sequelize.define('note', {
text: {
type: Sequelize.STRING
}
});
/*
用于判斷是否連接數(shù)據(jù)庫 運(yùn)行 node note.js
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
*/
/*
數(shù)據(jù)庫的操作
Note.sync().then(function(){
Note.create({text: 'hello tyy'});
}).then(function(){
Note.findAll({raw: true}).then(function(notes){
console.log(notes)
})})
Note.findAll({raw: true,where:{id:2}}).then(function(notes){
console.log(notes)
})
*/
module.exports.Note = Note;
在路由中將具體的路由抽離如下
var express = require('express');
var router = express.Router();
var Note = require('../model/note').Note
/* GET users listing. */
// 1.獲取所有的note: GET: /api/notes req: {} res: {stauts: 0, data: [{note1},{note2},{note3}]} {status: 1, errMsg: '失敗的原因'}
// 2.創(chuàng)建一個(gè)note: POST: /api/note/add req: {note: 'hello tyy'} res: {status :0} {status: 1, errMsg: '失敗的原因'}
// 3.修改一個(gè)note: POST: /api/note/edit req: {note: 'new note', id: 101}
// 4.刪除一個(gè)note: post: /api/note/delete req: {id: 101}
router.get('/notes', function(req, res, next) {
Note.findAll({raw: true}).then(function(notes){
console.log('---------------:'+notes)
res.send({status: 0,data:notes})
})
});
router.post('/notes/add', function(req, res, next){
var note = req.body.note;
Note.create({text:note}).then(function(){
res.send({status: 0})
}).catch(function(){
res.send({status: 1,errorMsg:'數(shù)據(jù)庫出錯(cuò)'
})
})
})
router.post('/notes/edit', function(req, res, next){
Note.update({text: req.body.note},{where:{id:req.body.id}}).then(function(){
res.send({status: 0})
})
})
router.post('/notes/delete', function(req, res, next){
Note.destroy({where:{id:req.body.id}}).then(function(){
res.send({status: 0})
})
})
module.exports = router;