当前位置:主页 > 脚本语言 > NodeJS >

Node.js连接mongo数据库上传文件的方法步骤

时间:2022-09-20 09:26:59 | 栏目:NodeJS | 点击:

效果

请添加图片描述

初始化

model 下创建index.js用于连接数据库时的信息

const mongo=require("mongoose");
const userSchema=new mongo.Schema({
    username:String,
    password:String,
    gender:String,
    tel:String,
    avatarUrl:String
})
const userModel=mongo.model('runoob',userSchema,'users')
module.exports=userModel

修改app.js文件里的信息

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// 连接数据库
const mongoose = require('mongoose'); // 引入 mongoose,用于连接数据库
mongoose.connect('mongodb://localhost:27017/runoob'); // 连接数据库

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//挂载路由
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

router下修改user.js文件

这里是处理客户端请求的核心,遵循REST架构风格

查找

增加

修改

删除

var express = require('express');
const db=require('../model/index')
const formidable=require('formidable')
const path=require('path')
var router = express.Router();
const bcrypt=require('bcryptjs')

// /* GET users listing. */

//查找
router.get('/:_id?',(req,res)=>{
  const {_id}=req.params;
  if(_id){
    console.log(_id);
    db
    // .findOne({_id:'6274ee9d620974ebd2122df8'})
    // .find({_id:_id})
    .findById(_id)
    .then(data=>{
      res.json({
        code:200,
        status:1,
        data,
      })
    })
  }else {
    db
        .find()
        .then(data=>{
          res.json({
            code:200,
            status:0,
            data
          })
        })
  }
})
//增加
router.post('/api/upload',(req,res,next)=>{

  const form=formidable({
    multiples: true,
    uploadDir: path.join(__dirname, '../static/upload'),
    keepExtensions: true,

  })
  form.parse(req,(err,fields, files)=>{
    if(err) {
      next(err);
      return;
    }
    const {name,password,gender,tel}=fields;
    const avatarUrl="/upload/"+ files.avatar.newFilename;//文件夹,包含上传文件
    if(!name || !password){
      res.json({
        code:200,
        status:1,
        message:"用户名或密码不能为空"
      })
    }else {
        db.findOne({username:name}).then(data=>{
        if(data==null){
          const hash=bcrypt.hashSync(password,10)
          new db({username:name,password:hash,gender,tel,avatarUrl})
              .save()
              .then(data=>{
                res.json({
                  code:200,
                  status:0,
                  message:data
                })
              })

        }else {
          res.json({
            code:200,
            status:1,
            message:"用户名已存在"
          })
        }
      })
    }
  })
   
})
 //修改
router.put('/:_id',(req,res)=>{
    const _id=req.params;
    const {username,password,gender,tel,avatarUrl}=req.body;
    db
    .updateOne({_id},{username,password,gender,tel,avatarUrl})
    .then((data)=>{
      res.json({
        code:200,
        status:0,
        message:"修改成功" 
      })
    })
 

})
//删除
router.delete('/:_id',(req,res)=>{
  const _id=req.params;
  db.deleteOne({_id}).then((data)=>{
    res.send({
      code:200,
      status:0,
      message:"删除成功"
    })
  })
})
module.exports = router;

创建上传文件保存文件夹

文件夹mondo-express下新建一个static/upload

在public下新建一个index.html 用于请求时的主页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>With <code>"express"</code> npm package</h2>
    <form action="users/api/upload" enctype="multipart/form-data" method="post">
        <div>name: <input type="text" name="name" /></div>
        <div>password:<input type="password" name="password"></div>
        <div>gender:<input type="text" name="gender"></div>
        <div> tel:<input type="text" name="tel"></div>
        <div>File: <input type="file" name="avatar" multiple="multiple" /></div>
      <input type="submit" value="Upload" />
    </form>
</body>
</html>

您可能感兴趣的文章:

相关文章