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

Node REPL加载Mongoose代码出现无限循环问题求助

问题解决方法

这个问题是Node.js REPL的.load命令对ES模块(import语法)的处理存在兼容性问题,会导致重复解析import语句陷入无限循环。以下是几种可行的解决方式:

方式一:改用CommonJS语法编写代码

将代码中的ES模块语法替换为CommonJS,REPL能正常加载执行:

const mongoose = require('mongoose');
const { Schema } = mongoose;
mongoose.set('strictQuery', false); 
mongoose.connect('mongodb://127.0.0.1:27017/moviesdb')
.then(() => {
    console.log("Connection Open")
})
.catch(err => {
    console.log("error")
    console.log(err)
})

const movieSchema = new Schema({
    title: String,
    year: Number,
    score: Number,
    rating: String,
});

const Movie = mongoose.model('Movie', movieSchema)
const amadeus = new Movie({title: 'Amadeus', year: 1986})

修改后再用node进入REPL执行.load index.js即可正常运行。

方式二:直接执行文件而非通过REPL加载

这是更稳妥的方式,直接在终端运行:

node index.js

这样既不会触发循环问题,还能直接看到数据库连接的日志输出,后续要操作模型的话,可以在代码末尾添加交互逻辑,或者用实验性参数启动REPL后手动导入模块。

方式三:启用ES模块支持的REPL(可选)

如果坚持要用ES模块语法在REPL中操作,可以启动REPL时添加实验性参数:

node --experimental-repl-await

进入REPL后手动执行import mongoose from 'mongoose';来导入模块,再逐步执行代码逻辑,避免用.load加载整个文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:40:32