后端无法连接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能够连接到后端。
我是初学者,如果这个问题对你们来说太简单了,对不起。
1条答案
按热度按时间ct3nt3jp1#
您正在为Model查询使用回调模式。这在V7.x中已被mongoose弃用。
您应该通过升级
package.json
并安装最新版本来确保您至少拥有mongoose V7。您可以使用
then().catch()
块或最好使用async/await
模式来检索数据,如下所示:字符串