导入 mongoose 时出现这样的错误
pkFactory: db.options?.pkFactory ?? utils_1.DEFAULT_PK_FACTORY, ^ SyntaxError: Invalid or unexpected token at Module._extensions..js (node:internal/modules/cjs/loader:1310:10) Node.js v18.17.0
这是 server.js 文件
import express from "express";
import mongoose from 'mongoose';
import {readdirSync} from "fs";
const morgan = require("morgan");
require("dotenv").config();
//create express app
const app = express();
// //db
// mongoose.connect(process.env.DATABASE, {
// // userNewUrlParser:true,
// // useFindAndModify:false,
// // useUNifiedTopology:true,
// // useCreateIndex:true,
// })
//apply middlewares
app.use(express.json());
app.use(morgan("dev"));
//you can use your own middleware like this
app.use((req, res, next) => {
console.log("this is my own middleware");
next();
});
//route
//it is importing whole fs module but we are using the readdireSync() function only
//so we can imort the readdireSync() by destructuring method
//so we will import only this function only
// import readdirSync like this import {readdirSync} from "fs";
readdirSync('./routes').map((r)=>{
app.use('/api',require(`./routes/${r}`))
});
//server port
const port = process.env.PORT || 4000;
// start listen to our server
app.listen(port, () => {
console.log(`server is running on port : ${port}`);
});
它是我的 package.json 文件
我尝试连接mongodb一些我发现添加
"type":module
的地方发现写入文件名与.mjs
remove -r esm
和不同的地方,但任何对我不起作用的地方请帮助我。
我在本地 MongoDB 和 MERN 项目中遇到了同样的问题,但使用以下方法修复了:
DATABASE_URL=mongodb://localhost:27017/exampleDB to
DATABASE_URL=mongodb://127.0.0.1:27017/exampleDB