mongoose數(shù)據(jù)庫
1.新建文件夾
2.npm init (package.json)
3.npm i node(node包)
4.安裝 koa koa-router mongoose koa-body(解析復(fù)雜數(shù)據(jù)請求)
5.新建一個app.js
const Koa = require('koa')
const Router = require('koa-router')//路由
const mongoose = require('mongoose')//數(shù)據(jù)庫
const koaBody =require('koa-body')
// 實例化koa Router
const app = new Koa()
const router = new Router()
// 連接數(shù)據(jù)庫
const db=require('./config').mongodb
mongoose.connect(db,{ useNewUrlParser: true ,useUnifiedTopology:true},(res)=>{
console.log('連接上了');
},(err)=>{
console.log(err);
})
// 引入api文件(先把這兩個給注釋掉,現(xiàn)在用不到)
//const user=require('./router/api/users')
//router.use('/api',user)
// 簡單配置路由
router.get('/',async ctx=>{
ctx.body="hello koa"
})
// 接收post參數(shù)解析
app.use(koaBody({multipart:true}))
app.use(router.routes(),router.allowedMethods())
const port=3000//端口號
app.listen(port,()=>{
console.log('正在監(jiān)聽端口',port);
})
6.創(chuàng)建config.js(這里寫的是從mongoose數(shù)據(jù)庫復(fù)制的)
module.exports={
mongodb:'mongodb+srv://<name>:<password>@cluster0.1mwgh.mongodb.net/listArr?retryWrites=true&w=majority'
}
就能運行koa會返回連接成功
這里進行的就是操作數(shù)據(jù)庫了
7.創(chuàng)建router/api/user.js
const Router= require('koa-router')
const router = new Router()
// 引入規(guī)則
const User = require('../../models/user')
router.post('/addlist', async ctx=>{
const newUser=new User({
name:ctx.request.body.name,
price:ctx.request.body.price,
introduce:ctx.request.body.introduce,
})
//存到數(shù)據(jù)庫
await newUser.save().then((res) => {
ctx.body=newUser
}).catch((err) => {
console.log(err);
})
})
module.exports=router.routes()
8.創(chuàng)建models/user.js(這個是我們王數(shù)據(jù)庫里面添加數(shù)據(jù)的規(guī)則)
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const userShema= new Schema({ //type:是數(shù)據(jù)類型,require:true為必填
name:{type:String,require:true},
price:{type:String,require:true},
introduce:{type:String,require:true},
date:{type:Date,default:Date.now}//每次添加成功當前的時間
})
module.exports=mongoose.model('user',userShema)
這個時候就可以把app.js中引入api文件給解除注釋
// 引入api文件
const user=require('./router/api/users')
router.use('/api',user)
就能進行數(shù)據(jù)添加了