Node.js+MongoDB开发CRUD程序遇未知编译错误,无具体错误信息求助
Let's break down the issues in your code and fix them one by one. The error stack points directly to line 13 of your Node.js file, and there are a couple of other potential pitfalls we'll address to prevent future problems.
1. Direct Cause of the Runtime Error: Wrong View Engine Setup
You used app.use() to set the view engine, but Express requires app.set() for configuration settings like view engines. app.use() is meant for mounting middleware, not setting app-wide configurations. This mismatch is the immediate reason for your runtime error.
Fix:
Replace this line:
app.use("view engine","ejs");
With:
app.set("view engine", "ejs");
2. Mongoose Model Definition Issue
You're defining the Mongoose model inside the POST route handler (/addbook), which means every time a request hits this route, you're trying to re-register the same model with Mongoose. This will cause unexpected errors after the first request, as Mongoose doesn't allow duplicate model registrations.
Fix:
Move the model definition to the global scope, right after you define the schema:
var booksSchema = new mongoose.Schema({ title: String, author: String }); // Define model once, outside routes var Book = mongoose.model("Book", booksSchema);
Then update your POST route to use this pre-defined model:
app.post("/addbook",function(req,res){ var title2 = req.body.title1; var author2 = req.body.author1; Book.create({title:title2,author:author2},function(err,newBook){ if(err){ console.log(err); res.status(500).send("Failed to create book"); } else{ res.send(newBook); } }); });
3. Add Mongoose Connection Error Handling
Your current MongoDB connection code doesn't include error handling, so if MongoDB isn't running or the connection fails, you won't get clear feedback. This makes it hard to debug connection-related issues.
Fix:
Add a promise-based error handler to your connection code:
mongoose.connect("mongodb://localhost:27017/practiceofmn") .then(() => console.log("Connected to MongoDB successfully")) .catch(err => console.error("MongoDB connection error:", err));
Corrected Full Node.js Code
Here's the complete, fixed version of your server code:
var express = require("express"), app = express(), bodyParser = require("body-parser"), mongoose = require("mongoose"); // MongoDB connection with error handling mongoose.connect("mongodb://localhost:27017/practiceofmn") .then(() => console.log("Connected to MongoDB successfully")) .catch(err => console.error("MongoDB connection error:", err)); app.use(bodyParser.urlencoded({extended:true})); // Correct view engine setup app.set("view engine", "ejs"); // Schema and Model definition (global scope) var booksSchema = new mongoose.Schema({ title: String, author: String }); var Book = mongoose.model("Book", booksSchema); app.get("/",function(req,res){ res.render("book"); }); app.post("/addbook",function(req,res){ var title2 = req.body.title1; var author2 = req.body.author1; Book.create({title:title2,author:author2},function(err,newBook){ if(err){ console.log(err); res.status(500).send("Failed to create book entry"); } else{ res.send(newBook); } }); }); app.listen(3000,function(){ console.log("Server is running on port 3000"); });
Notes on Your EJS View
Your book.ejs code is actually correct - no changes needed there. Just make sure you have the ejs package installed (run npm install ejs if you haven't already).
Steps to Test the Fix
- Make sure MongoDB is running locally on port 27017.
- Install any missing dependencies:
npm install express body-parser mongoose ejs. - Replace your server code with the corrected version above.
- Run the server:
node practiceofmongonode.js. - Visit
http://localhost:3000in your browser, submit the form, and you should see the created book object returned.
内容的提问来源于stack exchange,提问作者user12142401

