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

Node.js+Mongoose引入模块报错:Cannot use import statement outside a module

解决方法

1. 统一模块规范并配置项目类型

报错核心是CommonJS与ES模块混用,Node.js默认采用CommonJS规范,若文件中使用import语法但未配置模块类型,就会触发该错误。可任选以下一种方案统一规范:

方案A:继续使用CommonJS(与当前auth.js风格一致)

  • 确保所有文件均使用require/module.exports,禁止使用import/export
  • 检查User.js,若实际代码中用了import mongoose from "mongoose",将其替换为CommonJS写法

方案B:切换为ES模块

修改package.json,添加"type": "module"配置:

{
  "name": "inotebook",
  "version": "1.0.0",
  "description": "inotebook- your notebook on cloud",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "mongoose": "^8.1.1"
  }
}

之后所有文件需改用import/export,例如auth.js需调整为:

import express from "express";
const router = express.Router();
import User from "../models/User.js"; // ES模块需添加.js后缀

// 其余代码
export default router;

2. 修复User.js的语法错误

当前User.js缺少mongoose和Schema的引入,且字段配置有误,以下是两种规范下的修正版本:

CommonJS版本

const mongoose = require("mongoose");
const { Schema } = mongoose; // 从mongoose解构Schema

const UserSchema = new Schema({
  name: {
    type: String, // 字段类型需用type而非title
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now, // 设置默认值,无需手动传入
    required: true,
  },
});

module.exports = mongoose.model("user", UserSchema);

ES模块版本

import mongoose from "mongoose";
const { Schema } = mongoose;

const UserSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
    required: true,
  },
});

export default mongoose.model("user", UserSchema);

3. 修复auth.js的逻辑问题

当前用router.get处理用户创建不符合REST规范,且未处理异步操作,修正后代码如下(以CommonJS为例):

const express = require("express");
const router = express.Router();
const User = require("../models/User");

router.post("/", async (req, res) => {
  try {
    const user = new User(req.body); // 创建实例需加new关键字
    await user.save();  
    res.status(201).send(user);
  } catch (err) {
    res.status(400).send({ error: err.message });
  }
});

module.exports = router;

验证步骤

  1. 确保入口文件(index.js)已完成MongoDB连接配置
  2. 重启Node服务
  3. 用Postman或curl发送POST请求到/auth接口,携带用户数据测试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 10:22:39