Good day everyone, I am beginner in backend development, I encountered a problem trying to connect my server to my database. This is my code from my server:
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}) }) and this is the code from my database:
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 this is the reply i got from my terminal:
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... Please would appreciate your suggestions.
11 Answer
You are encountering a problem in connecting to Mongoose. Make sure to log the connection error first before any request to mongoose. try updating your connection code to this:
mongoose.connect("mongodb://127.0.0.1:27017/footballinfo"). then(()=>{console.log("Mongoose server has started") }) .catch((err)=>{ console.error(err) }) This will give you why your connection was unsuccessful. Also mongoose.connect() behaves asynchronously so handle that before making any request to the server.