我是新來的NodeJS和學習從udemy當然https://www.udemy.com/api-development/learn/v4/content
過程中使用的MongoDB(貓鼬)的API開發,但現在我想用Sequelize
表達的NodeJS API一個sequelize(DB)實例所有車型
mongoose
生病嘗試詳細解釋問題。 我有一個文件db.js
import mongoose from 'mongoose';
import config from './config';
export default callback => {
let db = mongoose.connect(config.mongoUrl);
callback(db);
}
i相sequelize代替它
import Sequelize from 'Sequelize';
import config from './config';
export default callback => {
let db = new Sequelize(config.dbname, config.dbuser, config.dbpassword, {
host: config.dbhost,
dialect: 'mariadb',
pool: {
max: 5,
min: 0,
idle: 10000
}
});
callback(db);
}
它需要這個數據庫實例,並將其傳遞到中間件和在routes.js控制器文件
import express from 'express';
import config from '../config';
import middleware from '../middleware';
import initializeDb from '../db';
import restaurant from '../controller/restaurant';
let router = express();
//connect to db
initializeDb(db => {
//internal middleware
router.use(middleware({config,db}));
// api routes
router.use('/restaurant',restaurant({config,db}));
});
export default router;
並在創建服務器時將此路由傳遞給app.use
import http from 'http';
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import config from './config';
import routes from './routes'; //her it imports the routes and pass it to app.use below
let app = express();
app.server = http.createServer(app);
// middleware
// parse application/json
app.use(bodyParser.json({
limit:config.bodyLimit
}));
// passport config
//api routes v1
app.use('/v1',routes); //here it pass the routes
var listener = app.server.listen(config.port,function(){
console.log(`Started on port ${listener.address().port}`);
});
export default app;
所以在這一點數據庫實例現在是我的控制器可以在這裏是如何: 這是控制器
import mongoose from 'mongoose';
import { Router } from 'express';
import Restaurant from '../model/restaurant';
export default({config,db}) => {
let api = Router();
// '/v1/restaurant' - Read
api.get('/',(req,res) => {
// i have db available here
});
return api;
}
在這一點上,我需要在模型數據庫實例,所以我可以只是一個導入控制器(迴歸模型控制器),而不是在控制器import Restaurant from '../model/restaurant';
使用DB實例,其中Restaurant
將sequelize模型
但因爲我沒有在模型中可用的數據庫,一個方法是在初始化數據庫模型文件,但我想如果有辦法獲得已經初始化的數據分析nce它會更好,在mongoose
它使用模式生成模型,但對於後續我需要有數據庫實例爲了創建模型,下面是貓鼬模型。
import mongoose from 'mongoose';
let Schema = mongoose.Schema;
let restaurantSchema = new Schema({
name:String
});
module.exports = mongoose.model('Restaurant',restaurantSchema);
任何幫助,將不勝感激,或者如果沒有這樣做,請提出一個更好的辦法