NodeJS 后端无法连接mongodb

bprjcwpo  于 9个月前  发布在  Node.js
关注(0)|答案(1)|浏览(106)

后端无法连接mongodb
我通过 Postman 测试,我的mongedb有数据
mongodb连接
它正常,如果测试/和发送“Hello World”,但当我测试/Data_Admin Postman发送[]回
这都是代码

// model

const mongoose = require("mongoose")
const Data_Admin_Shema = mongoose.Schema({
    id: {
        type: String,
        required : true
    },
    fullname: {
        type: String,
        required : true
    },
    lastname: {
        type: String,
        required : true
    },
    nick: {
        type: String,
        required : true
    },
    username: {
        type: String,
        required : true
    },
    password: {
        type: String,
        required : true
    },
    rank: {
        type: String,
        required : true
    },
})

exports.Data_Admin_Model = new mongoose.model("Data_Admin",Data_Admin_Shema)
// routes

const express = require("express")
const router = express.Router()
const {Data_Admin_Model} = require("../model/Data_Admin")

router.get("/",(req,res) => {
    res.send("Helo World")
})

router.get("/Data_Admin",async (req,res,next) => {
    Data_Admin_Model.find((err,Data_Admin) => {
        if (err) return next(err)
        res.json(Data_Admin)
    })
})

module.exports = router
// server

const express = require("express");
const cors = require("cors");

const mongoose = require('mongoose')

const app = express();

mongoose.set("strictQuery", false);

mongoose.connect('mongodb://127.0.0.1:27017/Data_since_Pro')
        .then(() => console.log('Yes app'))
        .catch((err) => console.error(err))

app.use(express.json())
app.use(cors());

const Data_Admin_Route = require("./routes/Data_Admins");

app.use("/",Data_Admin_Route);

app.listen(5000,() => console.log("app run"));

期望mongodb能够连接到后端。
我是初学者,如果这个问题对你们来说太简单了,对不起。

ct3nt3jp

ct3nt3jp1#

您正在为Model查询使用回调模式。这在V7.x中已被mongoose弃用。
您应该通过升级package.json并安装最新版本来确保您至少拥有mongoose V7。
您可以使用then().catch()块或最好使用async/await模式来检索数据,如下所示:

router.get("/Data_Admin", async (req, res, next) => {
   try{
      const Data_Admin = await Data_Admin_Model.find({});
      if(!Data_Admin.length){ //< length will be 0 if empty array
         return res.status(400).json({
            message: 'No documents found.'
         });
      }
      return res.status(200).json(Data_Admin);
   }catch(err){
      console.log(err);
      return res.status(500).json({
         message: 'Error on server.'
      });
   }
})

字符串

相关问题