NodeJS MongooseError:操作“infos.find()”在10000ms后缓冲超时

ecfsfe2w  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(101)

大家好,我是后端开发的初学者,我遇到了一个问题,试图连接我的服务器到我的数据库。这是我的服务器代码:

const express = require("express")
const {default:mongoose} = require("mongoose")

const app = express();
const Info = require("./models/info.js")

app.set("views engine", "ejs")
mongoose.connect("mongodb://127.0.0.1:27017/footballinfo").
then(()=>{console.log("Mongoose server has started")
})
.catch(()=>{
    console.log("Unsuccessful")
})

app.use(express.static("public"))
app.use(express.urlencoded())
app.get("/", async (req, res) => {
    const infos = await Info.find()
    res.render("index.ejs", {title:"Home", news})
})

这是我数据库里的代码

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

const infoSchema = new Schema(
    {
        title: {
            type: String,
            required:[true, "Title cannot be blank"]
        },
        snippet: {
            type: String,
            required:[true, "Snippet cannot be blank"]
        },
        body: {
            type: String,
            required: [true, "The Information is blank"]
        },
    },
    {timestamps: true}
)

const Info = mongoose.model("Info", infoSchema)

module.exports=Info

这是我从终端得到的回复:

server is running
Unsuccessful
C:\Users\go\Desktop\aid\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185
          const err = new MongooseError(message);
                      ^

MongooseError: Operation `infos.find()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:\Users\go\Desktop\aid\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185:23)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)
[nodemon] app crashed - waiting for file changes before starting...

请您提出建议。

cbeh67ev

cbeh67ev1#

您连接到Mongoose时遇到问题。在向mongoose发出任何请求之前,请确保首先记录连接错误。尝试将您的连接代码更新为:

mongoose.connect("mongodb://127.0.0.1:27017/footballinfo").
then(()=>{console.log("Mongoose server has started")
})
.catch((err)=>{
    console.error(err)
})

这将给予您连接失败的原因。另外,mongoose.connect()的行为是异步的,因此在向服务器发出任何请求之前都要处理它。

相关问题