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

Node.js中正确引入models多文件的方法及代码错误排查

问题描述

我在名为models的文件夹中创建了user.js和candidate.js两个文件,尝试使用const { db } = require('../models/User,Candidate');语句引入这两个文件时出现报错,请问正确的引入方式是什么?同时我的代码中是否还存在其他错误?

目录结构

  • 项目根目录
    • server.js
    • models/
      • user.js
      • candidate.js
    • routes/
      • auth.js
    • .env

candidate.js代码

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const candidateSchema = new Schema({
    candidate_name: {
        type: String,
        required: true
    },
    party_name: {
        type: String,
        required: true
    },

    image: {
    type: String,
        required: true}
},
    {
        image: true,
        collection: 'candidate'
    }
);


const candidate = 'candidate';
module.exports = mongoose.model(Candidate, candidateSchema)

server.js代码(已移除中间件代码)

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const Candidate = require('./Candidate');
const bodyParser = require('body-parser');
require('dotenv').config();

//import routes
const authRoutes = require('./routes/auth');
const { db } = require('../models/User,Candidate');

//app
const app = express();

// db
mongoose
  .connect(process.env.DATABASE,{
      useNewUrlParser: true,
      //useCreateIndex: true,
      useUnifiedTopology: true
   })
  .then(() => console.log('DB Connected'));

app.get("/candidate/get", (req, res) => {
  candidate.find((err, data) => {
    if (err) {
      res.status(500).send(err);
    } else {
      res.status(200).send(data);
    }
  });
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`Server is running on ${port}`)
});

问题解答

一、正确的文件引入方式

Node.js的require语法不支持单语句多文件引入,也不能用逗号分隔文件名。你需要按以下方式修正:

  1. 路径修正:server.js在根目录,models是同级文件夹,所以路径应该用./models/xxx(../表示上级目录,会导致路径错误)
  2. 分别引入模型:
// 引入User模型(假设user.js导出的是User)
const User = require('./models/user');
// 引入Candidate模型
const Candidate = require('./models/candidate');

另外,你代码里的const { db } = require(...)完全错误——你的模型文件导出的是Mongoose模型实例,并非包含db属性的对象,不需要解构赋值。

二、代码中的其他错误

1. candidate.js中的错误

  • 导出模型时使用未定义变量:你定义了const candidate = 'candidate';,但导出时写的是mongoose.model(Candidate, candidateSchema),Candidate是未声明的变量,会报错。正确写法:
// 方式一:使用已定义的变量
module.exports = mongoose.model(candidate, candidateSchema);
// 方式二:直接传入字符串
module.exports = mongoose.model('candidate', candidateSchema);
  • Schema配置项无效:配置对象里的image: true是无效属性,Mongoose没有这个选项,若需要自动生成时间戳,应该改成timestamps: true,不需要则直接删除:
{
  timestamps: true, // 可选,自动添加createdAt、updatedAt字段
  collection: 'candidate'
}

2. server.js中的错误

  • 模型引入路径错误:const Candidate = require('./Candidate');,模型文件在models/candidate.js,正确路径是./models/candidate(注意文件名大小写匹配)
  • 变量名不一致:app.get接口里用了candidate.find(...),但你引入的是Candidate(大写开头),应该统一为Candidate.find(...)
  • 数据库连接缺少错误处理:mongoose.connect只处理了成功情况,需添加失败捕获:
mongoose
  .connect(process.env.DATABASE, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => console.log('DB Connected'))
  .catch(err => console.error('DB连接失败:', err));
  • 冗余错误代码:const { db } = require('../models/User,Candidate');完全无效,直接删除
  • 未使用的模块:引入了cors和body-parser但未配置中间件,要么删除引入,要么添加配置:
// 配置cors中间件
app.use(cors());
// 配置body-parser(或用express内置的express.json())
app.use(bodyParser.json());
// 替代方案:express内置解析
app.use(express.json());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:09:57