mongodb数据库操作

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值