基本布局的建立
express my-app
cd my-app
npm install -S mongoose
一、布局的变动
/my-app
- bin
| main.js ##程序的入口
- models
| index.js ## Schema集中定义
+ routes ## Express的Router
mongo.js ## mongo的模型定义
app.js ## express的配置管理
package.json
...
二、Schema定义集中
【/models/index.js】
let BookSchema={name:String,price:Number}
module.exports={BookSchema}
三、mogoose的模型定义
【/mongo.js】
const mongoose=require('mongoose')
const model=require('./models')
let Book=mongoose.model("book",model.BookSchema)
四、入口程序
【/main.js】
const mongoose=require('mongoose')
const mongo=require('../mongo')
const app=require('../app')
const http=require('http')
let mongoUrl='mongodb://localhost:27017/test12'
let httpPort=3000
let server=http.createServer(app)
mongoose.connect(mongoUrl,err=>{
server.listen(httpPort)
})
server.on('listening',()=>{
console.log(`express start at ${server.address().host} :${server.address().port}`)
})
server.on('error',(err)=>console.log("express error"))
mongoose.connection.on('open',function () {
})
mongoose.connection.on('open',function () {
console.log(`mongoose connected in ${mongoose.connection.host}:${mongoose.connection.port}`)
})
mongoose.connection.on('error',function (err) {
console.log("mongoose connection error")
})
五、express与mongoose的对接
【routes/book.js 片段】
var express = require('express');
var router = express.Router();
const mongoose=require('mongoose')
let Book=mongoose.model('book')
router.get('/', function(req, res, next) {
Book.find({},function (err,newBook) {
res.json(newBook);
})
});
网友评论