#面向过程的代码书写、用来操作数据库
const express = require( 'express' );
const router = new express.Router();
// database 操作 --start
// 1. 安装mongoose cnpm i mongoose -S/-D
// 2. 引入mongoose
const mongoose = require( 'mongoose' );
const Schema = mongoose.Schema
// 3. 连接数据库
mongoose.connect( 'mongodb://127.0.0.1:27017/1903', ( error ) => {
if( error ){
throw error
}else {
console.log( 'database is connected~~' )
}
})
//4. 创建骨架( Schema ) 不能操作数据库
const userSchema = new Schema({
// 这个骨架的数据模型 ---- mySql中字段的定义
username: String,
password: String
})
//5. 创建模型 - 可以操作数据库
// const userModel = mongoose.model( 集合的名称[复数],骨架 )
const userModel = mongoose.model( 'users',userSchema )
//6. 创建实体 - 可以影响数据库
const user = new userModel()
// 数据 CRUD - 增
// user.username = 'Gabriel Yan',
// user.password = 123
// user.save()
// 数据 CRUD - 查
// userModel.find({},( error, result) => {
// if( error ) throw error
// console.log( result )
// })
// 数据 CRUD - 改
// userModel.find({ username: 'yyb' },( error , result ) => {
// if( error ) throw error
// const _id = result[0]._id
// // 修改
// userModel.findById( _id, ( error, doc ) => {
// if( error ) throw error
// doc.username = "Gabriel Yan"
// doc.save( ( error ) => {
// if( error ) throw error
// console.log( '数据修改成功' )
// })
// })
// })
// 数据库 CRUD - 删
// userModel.find({ username: 'Gabriel Yan' },( error , result ) => {
// if( error ) throw error
// const _id = result[0]._id
// // 修改
// userModel.findById( _id, ( error, doc ) => {
// if( error ) throw error
// doc.remove( ( error ) => {
// if( error ) throw error
// console.log( '数据删除成功' )
// })
// })
// })
// database 操作 --end
const db = require('../db')
//打造接口
router.get('/',( req,res,next ) => {
const { username,password } = req.query
userModel.find({},( error, result ) => {
const flag = result.some(( item )=> {
return item.username === username
})
console.log( flag )
if( flag ){
//这个表示数据库有这条数据
res.render( 'register', {
data: JSON.stringify( {
ret: true, // 身份验证 权限验证
status: 2 // 0 表示失败 1表示成功 2表示用户名重复
} )
})
}else{
// 表示数据库没有这条数据
user.username = username,
user.password = password
user.save()
res.render( 'register', {
data: JSON.stringify( {
ret: true, // 身份验证 权限验证
status: 1 // 0 表示失败 1表示成功 2表示用户名重复
} )
})
}
})
})
module.exports = router