mongodb下载/安装
mongoose npm install --save mongoose
mongoose 数据库连接
const mongoose = require('mongoose')
const DB_RUL = 'mongodb://localhost:27017/koa2'
mongoose.connect(DB_RUL, function(err){
if(err){
console.warn('数据库连接失败:'+err)
}else{
console.log('数据库成功连接到:'+DB_RUL)
}
})
module.exports = mongoose
koa-router 路由 npm install --save koa-router
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const mongoose = require('../config')
const router = new Router()
http://cnodejs.org/topic/548e54d157fd3ae46b233502
定义创建数据表
定义创建数据表
//创建一个Schema
const createSchema = mongoose.Schema({
name: {type: String, required: true },
age: {type: Number, required: true }
})
const User = mongoose.model('users', createSchema)
数据的简单查找
User.find({}, function(err, doc){
console.log(doc)
})
新建
User.create({
name : 'afacode',
age: 19 + Math.random()
}, function(err, doc){
if(err){
console.log(err)
}else{
console.log(doc)
}
})
先这样