使用Node.js+Express+MongoDB开发SPA时遇MissingSchemaError求助
Hey there! I see you're stuck with a MissingSchemaError while building your SPA—let's get this sorted out quickly.
The Root Cause
The issue is that your monitoringController.js doesn't know about the schema you defined in monitoring.model.js. Mongoose doesn't automatically detect and load model files from your project; you have to explicitly make the controller aware of the model's existence.
Two Simple Fixes
Option 1: Import the Model File Directly in the Controller
Add this line at the top of monitoringController.js (make sure the file path matches where your monitoring.model.js is located—adjust if it's in a subfolder like ./models/):
const express = require('express'); const mongoose = require('mongoose'); require('./monitoring.model'); // Add this line const monitoring = mongoose.model('monitoring'); // ... rest of your code
Option 2: Export the Model from Its File (Recommended for Clarity)
Modify monitoring.model.js to export the model instead of just registering it:
const mongoose = require('mongoose'); var monitoringSchema = new mongoose.Schema({ techName: { type: String }, Customer: { type: String }, Description: { type: String } }); module.exports = mongoose.model('monitoring', monitoringSchema); // Export the model
Then in monitoringController.js, import it directly instead of using mongoose.model():
const express = require('express'); const mongoose = require('mongoose'); const monitoring = require('./monitoring.model'); // Import the model directly // ... rest of your code
Why This Works
When you call mongoose.model('monitoring'), Mongoose checks its internal registry for a model with that name. If you haven't imported the file where you registered the schema (or imported the exported model), Mongoose has no idea the schema exists—hence the MissingSchemaError.
The second option is better for readability, especially as your project grows, since it makes it clear exactly which models your controller is using.
内容的提问来源于stack exchange,提问作者Joel D

