Mongo基本使用

发布于:2024-10-13 ⋅ 阅读:(135) ⋅ 点赞:(0)

连接数据库使用Studio 3T图形化工具

简单实用:express
app.js

// var express = require('express');
// var bodyParser = require('body-parser');

// // 创建项目实例
// const app = express();
// // 加载路由控制
// var routes = require('./index');

// // 定义数据解析器
// // parse application/x-www-form-urlencoded           body-parser  插件 数据问题
// app.use(bodyParser.urlencoded({ extended: false }));
// // parse application/json
// app.use(bodyParser.json());

// // 跨域等
// app.all('*', function (req, res, next) {
//     res.header("Access-Control-Allow-Origin", "*");
//     res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
//     res.header("Access-Control-Allow-Headers", "X-Requested-With");
//     res.header('Access-Control-Allow-Headers', ['mytoken', 'Content-Type']);
//     next();
// });

// // 匹配路径和路由
// app.use('/', routes);


// app.listen('8080', function () {   //此处的8080 需要和vue项目中的target 端口号后缀一模一样才可。
//     console.log("8080");
// })

// module.exports = app;

// --------------------------------

// vite 工作原理

const Koa = require('koa')
const app = new Koa()
const fs = require('fs')
const path = require('path')

// 中间件配置
// 处理路由
app.use(async (ctx)=>{
  const { url } = ctx.request
  // 首页请求
  if (url === '/') {
    // 加载index.html
    ctx.type = 'text/html'
    ctx.body = fs.readFileSync('../index.html', 'utf8')

  } else if(url.endsWith('.js')) {
    // js文件加载处理
    const p = path.join(__dirname, url)
    ctx.type = 'application/javascript'
    ctx.body = fs.readFileSync(p, 'utf8')
  }
})

app.listen(3000, ()=>{
  console.log('vite-stup')
})

module.exports = app

同目录下创建

var express = require('express');
var router = express.Router();


/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', { title: 'Express' });
});


var mongoose = require('mongoose')
//链接test1的数据
var url = "mongodb://worker:XX/test1?authMechanism=SCRAM-SHA-1&authSource=admin"      //连接MongoDB
console.log(url)
mongoose.set('strictQuery', true)

mongoose.connect(url, async function (err,client) {
  if (!err) {
    console.log('+++++++++连接成功!')
   
    // var type1 = { name: String, sex: String, chinese: Number, math: Number, english: Number }
    // var dataLists = mongoose.model('t1', carSchema)
    // let a = await mongoose.model('t1', carSchema).find()
    // console.log('result',a);
    // mongoose.model('test1', carSchema).find({},null).toArray(function(err, result) { // 返回集合中所有数据
    //       if (err) throw err;
    //       console.log('result',result);
    //       client.close();
    //   });
    // client.collection("t1").find().toArray(function(err, result) { // 返回集合中所有数据
    //     if (err) throw err;
    //     console.log('result',result);
    //     client.close();
    // });
  }
})

// // 数据类型
// var type = { name: String, sex: String, chinese: Number, math: Number, english: Number }
// let carSchema = new Schema({
//   name: { type: String },
//   sex: { type: String },
//   chinese: {
//       type: Number,
//   }
// })
// var mgs = mongoose.model('test1', type)
const Schema = mongoose.Schema;
let carSchema = new Schema({
  name: { type: String },
  sex: { type: String },
  chinese: {
      type: Number,
  }
})
// var dataLists = mongoose.model('test1', carSchema)

// module.exports = dataLists
// module.exports = mgs
exports.T1 = mongoose.model('test1', carSchema)

创建index,主要是增删改查 路由

var express = require('express');
var router = express.Router();
let dataLists = require('./mongo')  //引入mongo.js 文件

// 添加新增  /list  为自定义接口名
 router.post('/list', function (req, res) {
     var obj = req.body
     dataLists.create(obj, function (err, result) {
         if (!err) {
             res.send(result);
         }
     })
 })
// 查询
router.post('/querys', function (req, res) {
    console.log(req)
    var obj = req.body
    dataLists.find(obj, function (err, result) {
        if (!err) {
            res.send(result);
        }
    })
})
// 修改
router.post('/modify', function (req, res) {
    console.log(req)
    var obj = req.body
    dataLists.findOneAndUpdate({ _id: obj._id }, obj, function (err, result) {
        if (!err) {
            res.send(result)
        }
    })
})
// 删除
router.post('/deleds', function (req, res) {
    var obj = req.body
    console.log(obj)
    for (let i = 0; i < obj.length; i++) {
        dataLists.deleteOne({ _id: obj[i] }, function (err, result) {
            if (!err) {
                res.send(result)
            }
        })
    }

})

module.exports = router   

前端页面Vue直接调用
端口号一致

axios.get("http://localhost:6001/api/getinfo").then(res => {
      console.log('res----', res)
      if(res.data.code == 200) {
        studentList.value = res.data.list
        console.log('studentList.value', studentList.value)
      }
        // if (res.data.code == 200) {
        //   this.list = res.data.list;
        // } else {
        //   alert("FAIL");
        // }
    });

网站公告

今日签到

点亮在社区的每一天
去签到