You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中Mongoose创建MongoDB文档的位置及无效果问题排查

Fixing Mongoose Document Saving Issue & Project Structure Best Practices

Hey there! Let's tackle your problem from two angles: first getting your MongoDB documents to actually save, then figuring out the right place to create document instances in your project.

Why Your Documents Aren't Showing Up in MongoDB Compass

Your current setup has a few key issues that are preventing data from being saved:

  1. Asynchronous Connection Race Condition
    Mongoose's connect() is asynchronous, but your model code runs immediately—before the database connection is fully established. When you call test1.save() right after defining the model, there's no active connection to MongoDB yet, so the operation fails silently.

  2. Lack of Error & Success Feedback
    Your save callback only handles errors if they occur, but you're not logging success or connection status. You have no way to tell if the connection succeeded or if the save failed.

  3. Automatic Collection Naming
    Mongoose automatically pluralizes model names for collections. Your Test model will map to a tests collection (not Test), so you might be looking in the wrong place in Compass!

Step-by-Step Fixes

1. Fix the Database Connection Flow

First, update your index.js to ensure the connection is fully established before running any database operations, and add proper logging:

const mongoose = require("mongoose");
const express = require('express');
const app = express();

// Connect to MongoDB with proper promise handling
mongoose.connect("mongodb://localhost:27017/db")
  .then(() => console.log("✅ Successfully connected to MongoDB"))
  .catch(err => console.error("❌ MongoDB connection failed:", err));

// Import routes (we'll create these next)
const testRoutes = require('./routes/test');
app.use('/api/test', testRoutes);

// Start server
app.listen(3000, () => {
  console.log("🚀 Server running on port 3000");
});

Note: I added the default MongoDB port 27017 explicitly for clarity—make sure your local MongoDB is running on this port.

2. Refactor Your Model to Be Reusable

Your model file should only define the schema and export the model—not create instances or save data directly. Update /models/Test.js:

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

const mySchema = new Schema({
  name: String,
  count: Number
});

// Export the model so other files can use it
module.exports = mongoose.model("Test", mySchema);

3. Create Document Instances in Routes (or Services)

The right place to create and save documents is in your route handlers (or a dedicated service layer if your logic gets complex). Create a /routes/test.js file:

const express = require('express');
const router = express.Router();
const Test = require('../models/Test');

// Example route to create a test document
router.post('/create', async (req, res) => {
  try {
    // Create a new instance of the Test model
    const test1 = new Test({ name: "Clinton", count: 5 });
    // Save it to the database (using async/await for cleaner code)
    await test1.save();
    
    console.log("📄 Document saved successfully");
    res.status(200).json({ message: "Document saved", data: test1 });
  } catch (err) {
    console.error("❌ Failed to save document:", err);
    res.status(500).json({ error: "Failed to save document" });
  }
});

module.exports = router;

4. Test the Setup

  1. Make sure your local MongoDB service is running (run mongod in a separate terminal if it's not).
  2. Start your Node server: node index.js
  3. Send a POST request to http://localhost:3000/api/test/create (use Postman, curl, or a frontend form).
  4. Check MongoDB Compass: connect to mongodb://localhost:27017, look for the db database, then the tests collection—your document should be there!

Here's a standard structure that keeps your code organized:

your-project/
├── index.js          # Entry point: connects to DB, starts server, imports routes
├── models/           # All schema/model definitions (only export models here)
│   └── Test.js
├── routes/           # Route handlers (create/save/fetch documents here)
│   └── test.js
├── services/         # Optional: for complex business logic (e.g., TestService.js)
└── controllers/      # Optional: split route logic into controllers if routes get crowded
  • Models: Define data shapes and export Mongoose models—no data operations here.
  • Routes/Controllers: Handle HTTP requests, create document instances, and interact with models.
  • Services: (Optional) If you have complex logic (like validation, data transformation), put it here instead of cluttering routes.

内容的提问来源于stack exchange,提问作者MarcL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:42:23