将Mongoose连接导出到另一个文件中。

huangapple go评论57阅读模式
英文:

Exporting Mongoose connection to a different file

问题

当前文件/文件夹结构:

第1部分 - 创建mongoose连接
路径:myApp/src/db/mongoose.js

import mongoose from "mongoose";

mongoose.set("strictQuery", true);

mongoose.connect("mongodb://localhost:27017/task-manager-api", { useNewUrlParser: true }, () => {
  console.log("connected to database");
});

module.exports = mongoose; // 这是冗余的,没有分配给一个变量

第2部分 - 在运行express的文件中导入它
路径:myapp/index.js

import express from "express";
import "./src/db/mongoose";

const app = express();
const port = 3000;

app.use(express.json());

app.listen(port, () => {
  console.log("listening on port 3000");
});

错误:
无法找到模块"myApp/src/db/mongoose",从"myApp/index"导入

这是我尝试过的:

  1. 我尝试使用const mongoose = require("mongoose"),然后module.exports = mongoose将连接移到index.js文件中,但仍然没有运气。
  2. 大量搜索谷歌以查找是否在任何地方维护了一个单独的mongoose连接文件。
  3. 我查找了如何在ES6中使用require模块,但仍然没有运气。
// import { createRequire } from "module";
// const require = createRequire(import.meta.url);

任何帮助/建议都将不胜感激。谢谢。

预期输出:

  1. Mongoose连接导入到index.js中
英文:

Current file/folder structure:

Part 1 - Create a mongoose connection

path: myApp/src/db/mongoose.js

import mongoose from "mongoose";

mongoose.set("strictQuery", true);

mongoose.connect("mongodb://localhost:27017/task-manager-api", { useNewUrlParser: true }, () => {
  console.log("connected to database");
});

module.exports = mongoose; //this is redundant without assigning to a variable

Part 2 - Importing it in a file where I run express
path: myapp/index.js

import express from "express";
import "./src/db/mongoose";

const app = express();
const port = 3000;

app.use(express.json());

app.listen(port, () => {
  console.log("listening on port 3000");
});

Error:
Cannot find module "myApp/src/db/mongoose" imported from "myApp/index"

Here's what I have tried:

  1. I tried to use const mongoose = require("mongoose") and then module.exports = mongoose to move the connection to the index.js file but still no luck
  2. A tonne of google search to find if a separate mongoose connection file is maintained anywhere
  3. I looked up how to use require module in ES6 but still no luck
// import { createRequire } from "module";
// const require = createRequire(import.meta.url);

Any help/advice would be highly appreciated. Thank you.

Expected output:

  1. Mongoose connection imported into index.js

答案1

得分: 1

我会看一下做类似以下操作:

  • 将您的 mongoose 连接封装在一个导出的函数中
  • 在您的 index.js 中导入 connect 函数并调用它

代码可能会像这样(未经测试!):
mongoose.js:

export const connect = async () => {
  await mongoose.connect("mongodb://localhost:27017/task-manager-api", {
    useNewUrlParser: true
  });
};

index.js:

import express from "express";
import { connect } from "<...relevant_path_here...>/mongoose";

const app = express();
const port = 3000;

app.use(express.json());

const start = async () => {
  try {
    await connect();
    app.listen(port, () => {
      console.log("listening on port 3000");
    });
  } catch (error) {
    console.error(error);
    process.exit(1);
  }
};

start();
英文:

I'd look at doing something along the lines of

  • wrapping your mongoose connect up in an exported function
  • Import the connect function in your index.js and call it

The code may end up looking like this (Not tested!):
mongoose.js:

export const connect = async () =&gt; {
	await mongoose.connect(&quot;mongodb://localhost:27017/task-manager-api&quot;, {
		useNewUrlParser: true
	});
};

index.js


import express from &quot;express&quot;;
import {connect} from &quot;&lt;...relevant_path_here...&gt;/mongoose&quot;;

const app = express();
const port = 3000;

app.use(express.json());

const start = async () =&gt; {
  try {
    await connect();
    app.listen(port, () =&gt; {
        console.log(&quot;listening on port 3000&quot;);
    });
  } catch (error) {
    console.error(error);
    process.exit(1);
  }
};

start();

huangapple
  • 本文由 发表于 2023年1月9日 21:52:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75058253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定