• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Node.js服务端06-MongoDB和综合使用

武飞扬头像
懋学的前端攻城狮
帮助2

安装社区版

www.mongodb.com/try/downloa…

学新通

进入bin目录进行安装

调整一下路径,方便全局运行

sudo cp /Users/xxx/xxx/mongodb-macos-x86_64-6.0.8/bin/* /usr/local/bin/

创建数据库目录和日志目录

sudo mkdir -p ~/data/db


sudo mkdir -p ~/data/log/mongodb

设置用户权限以防出现读写问题

sudo chown 用户名 ~/data/db
sudo chown 用户名 ~/data/log/mongodb

测试运行

mongod --dbpath ~/data/db --logpath ~/data/log/mongodb/mongo.log --fork

学新通

Node.js操作MongoDB

1、安装mongoose

2、创建配置文件

//连接数据库
const mongoose = require("mongoose")

mongoose.connect('mongodb://localhost:27017/node_backend')
//插入集合和数据,数据库会自动创建

3、www引入

//引入数据库模块
require('../config/db.config')

4、创建模型

const mongoose = require("mongoose")
const Schema = mongoose.Schema

const UserType = {
  username: String,
  password: String,
  age: Number
}

const UserModel = mongoose.model('user', Schema(UserType))
// 模型user 将会对应 users集合 (自动的)
module.exports = UserModel

5、使用

创建并添加数据

router.post('/user/add', (req, res, next) =>{
  console.log(req.body);
  //插入数据库
  // 1.创建一个模型(user),一个一个地对应数据库的集合(users)
  const {username, password, age} = req.body
  UserModel.create({
    username, password, age
  }).then(data => {
    console.log(data);
  })
  
  res.send({
    ok:1
  })
})

更新一条数据

router.post('/user/update/:myid', (req, res, next) => {
  console.log(req.body, req.params);
  const {username, password, age} = req.body
  //更新一条数据
  UserModel.updateOne({_id:req.params.myid}, {
    username, password, age
  }).then(data => {
    console.log(data);
    
  })
  res.send({
    ok:1
  })
})

删除一条数据

router.get('/user/delete/:id', (req, res, next) => {
  // const {username, password, age} = req
 
  UserModel.deleteOne({_id:req.params.id}).then(data => {
    console.log(data);
    res.send({
      ok:1
    })
  })
})

查询所有数据

router.get('/user/list', (req, res, next) => {
  UserModel.find().then(data => {
    console.log(data);
    res.send({
      data
    })
  })
})

查询带页和数量参数

router.get('/user/list', (req, res, next) => {
  console.log(req.query);
  const {page, limit} = req.query
  //.skip().limit(req.query.limit)用于应对page=xxx&limit=xxx, skip=(page - 1) * limit 跳过的数
  UserModel.find().skip((page - 1) * limit).limit(limit).then(data => {
    console.log(data);
    res.send({
      data
    })
  })
})

接口规范与业务分层

RESTful架构:简单来说URL地址只包含名词表示资源,使用http动词表示动作进行操作资源,通过请求方法判断增删改查(get 查 put更新 delete删 post增,具体公司具体分析,我们小公司就只有get post)

SVC:

Service:主要处理增删改查功能 

Controller:处理后端的基本逻辑

View:展示内容

router:负责请求分发给C层

拆分后的代码如下

Controller

const UserService = require("../services/UserService");

const UserContrller = {
  addUser: async(req, res, next) =>{
    console.log(req.body);
    
    const {username, password, age} = req.body
    
    await UserService.addUser(username, password, age)
    res.send({
      ok:1
    })
  },

  update: async(req, res, next) => {
    console.log(req.body, req.params);
    const {username, password, age} = req.body
    await UserService.update(req.params.myid ,username, password, age)
    res.send({
      ok:1
    })
  },

  deleteUser: async(req, res, next) => {
    // const {username, password, age} = req
    await UserService.deleteUser(req.params.id)

    res.send({
      ok:1
    })
  },

  getUser: async(req, res, next) => {
    console.log(req.query);
    const {page, limit} = req.query
    const data = await UserService.getUser(page, limit)
    res.send({
      data
    })
  }
}

module.exports = UserContrller

Service

const UserModel = require("../model/UserModel");


const UserService = {
  addUser:(username, password, age) => {
    //插入数据库
    // 1.创建一个模型(user),一个一个地对应数据库的集合(users)
    return UserModel.create({
      username, password, age
    }).then(data => {
      console.log(data);
    })
  },

  update:(_id, username, password, age) => {
    //更新一条数据
    return UserModel.updateOne({_id}, {
      username, password, age
    }).then(data => {
      console.log(data);
      
    })
  },

  deleteUser:(_id) => {
    return UserModel.deleteOne({_id}).then(data => {
      console.log(data);
      
    })
  },

  getUser:(page, limit) => {
    //.skip().limit(req.query.limit)用于应对page=xxx&limit=xxx, skip=(page - 1) * limit 跳过的页数
    return UserModel.find().skip((page - 1) * limit).limit(limit).then(data => {
      console.log(data);
      
    })
  }
}

module.exports = UserService

router

router.post('/user', UserContrller.addUser)

router.put('/user/:myid', UserContrller.update)

router.delete('/user/:id', UserContrller.deleteUser)

router.get('/user', UserContrller.getUser)

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbcagc
系列文章
更多 icon
同类精品
更多 icon
继续加载