pkFactory: db.options?.pkFactory ?? utils_1.DEFAULT_PK_FACTORY,^ SyntaxError:Module._extensions..js 处的标记无效或意外

问题描述 投票:0回答:1

导入 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}`);
});

enter image description here

它是我的 package.json 文件

enter image description here

当我取消注释猫鼬导入时,它工作正常吗?为什么?
enter image description here

我尝试连接mongodb一些我发现添加

"type":module 
的地方发现写入文件名与
.mjs

和 package.json 不同的地方
remove -r esm
和不同的地方,但任何对我不起作用的地方请帮助我。

node.js mongodb syntax-error
1个回答
0
投票

我在本地 MongoDB 和 MERN 项目中遇到了同样的问题,但使用以下方法修复了:

  1. 问题很可能出在 mongoose 版本中(我刚刚降级了)
  2. 确保 .env 文件应为:(更改)
DATABASE_URL=mongodb://localhost:27017/exampleDB to
DATABASE_URL=mongodb://127.0.0.1:27017/exampleDB
  1. 修改数据库连接代码,如https:linkedin artical
© www.soinside.com 2019 - 2024. All rights reserved.