我在 Node.js 应用程序中遇到错误,我尝试从
app.js
导入 db.js
中的模块,但失败并显示错误消息:
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'path/src/db' imported from /path/src/app.js
但是,指定目录中存在
db.js
文件。
app.js
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import './db'
// Execute express
const app = express();
// Define PORT
const PORT = process.env.PORT || 8001;
//Middlewares
dotenv.config();
app.use(express.json());
app.use(cors());
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', (req, res) => {
res.send('Welcome buddy!');
});
app.listen(PORT, () => {
console.log(`App running on http://localhost:${PORT}/`);
});
db.js
import mongoose from "mongoose";
// connect to the database
mongoose
.connect(`${process.env.MONGO_URI}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000, // Timeout after 5s
})
.then(() => {
console.log('successfully connected to the db!');
})
.catch((err) => {
console.log('failed to connect with db!', err);
});
我已确保这两个文件位于正确的目录中。可能是什么原因导致此问题?我该如何解决?
如果我将数据库连接代码直接移至
app.js
,它就可以正常工作。
您应该从
db.js
将 mongoose 连接导出为函数,然后在 app.js
中使用它
在 db.js 中
import mongoose from "mongoose";
// connect to the database
const connectDb = async () => {
mongoose
.connect(`${process.env.MONGO_URI}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000, // Timeout after 5s
})
.then(() => {
console.log('successfully connected to the db!');
})
.catch((err) => {
console.log('failed to connect with db!', err);
});
}
module.exports = {connectDb};
并在
app.js
中使用它:
import { connectDb } from '.path-to-file/db';
connectDb();