导出Mongoose模型时遇TypeError: User is not a constructor,排查无果求助
Hey there, let’s troubleshoot this together! I know it’s frustrating when you’ve gone through all the common fixes and still hit a wall with your Mongoose setup. Let’s start by laying out your code clearly and walking through some easy-to-overlook issues that might be causing the problem.
Your Code Snippets
First, let’s organize the code you shared for clarity:
models/index.js
require('./users');
models/users.js
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const UserSchema = new Schema({ firstname: String, // ... other fields }); module.exports = mongoose.model('User', UserSchema);
routes/signup.js
const mongoose = require('mongoose'); const Schema = mongoose.Schema; // ... rest of your signup route code
Key Issues to Re-Check
Even if you think you’ve covered these, let’s verify each one—small oversights often cause these kinds of problems:
No MongoDB connection setup: Before your app can use the User model, Mongoose needs to be connected to your database. Make sure your entry file (like
app.jsorserver.js) has a connection block like this:mongoose.connect('mongodb://localhost/your-database-name') .then(() => console.log('Successfully connected to MongoDB')) .catch(err => console.error('MongoDB connection error:', err));Without this, your model won’t be able to interact with the database at all.
Missing User model import in signup route: Right now your
signup.jsis importing Mongoose and Schema, but it’s not pulling in the User model you defined. You need to add this line (adjust the path if your folder structure is different):const User = require('../models/users');Without importing the model, you can’t create or query User documents in your signup route.
Model export/import inconsistency: Your
models/index.jsis just requiring the users model, but not exporting it. This can lead to issues if you’re trying to import models fromindex.jselsewhere. Try updating it to:// models/index.js module.exports.User = require('./users');Then in your signup route, import it as:
const { User } = require('../models');This ensures consistent model access across your app.
Incorrect file paths: Double-check the relative path when requiring the User model in
signup.js. Ifsignup.jslives inroutes/andusers.jsis inmodels/, the path must be../models/users(the../moves up one directory fromroutes/to the root). A wrong path means the model never loads.Syntax errors in your Schema: The
...in your UserSchema suggests there are other fields—make sure all fields are properly formatted (no missing commas, valid data types, etc.). A tiny syntax mistake here can break the entire model registration.
If none of these fix the issue, could you share the exact error message you’re getting and the full code for routes/signup.js? That will help narrow things down even more.
内容的提问来源于stack exchange,提问作者Orlando Morales-Cochran

