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

使用Node.js+Express+MongoDB开发SPA时遇MissingSchemaError求助

Fixing the MissingSchemaError in Your Node.js/Express/MongoDB SPA

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:57:54