【问题标题】:Mongoose one connection to the db for the whole App猫鼬一个连接到整个应用程序的数据库
【发布时间】:2021-07-30 03:02:31
【问题描述】:

我正在观看 Mosh hamedani 的 Nodejs 课程,我注意到他在 index.js 中只使用了一个与 mongo db 的连接,并使用不同的路由来处理不同的 api 调用,这就是 index.js:

 const mongoose = require("mongoose");
const genres = require("./routes/genres");
const customers = require("./routes/customers");
const express = require("express");
const app = express();

mongoose
  .connect("mongodb://localhost/vidly") // the db name
  .then(() => console.log("connected to db ..."))
  .catch((err) => console.log(err.message));

app.use(express.json());

//simple routers
app.use("/api/genres", genres);
app.use("/api/cutomers", customers);

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

还有这个主要代码和genres.js中的get方法之一:

 const mongoose = require("mongoose");
const express = require("express");
const router = express.Router();

const Genre = mongoose.model(
  "Genre",
  new mongoose.Schema({
    name: {
      type: String,
      required: true,
      minlength: 5,
      maxlength: 20,
    },
  })
);
router.get("/", async (req, res) => {
  const genres = await Genre.find().sort("name");
  res.send(genres);
});
  //other codes
module.exports = router;

我的问题是,genres.js 如何在没有连接声明的情况下连接到索引 js 中的同一个数据库,以及它是如何工作的?

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    假设您只有一个数据库。您可以为该数据库创建一个文件,并在建立连接后导出连接。

    例如,您将拥有db.js

    const mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/foo_db');//I would use an environment variable instead of a string for security. 
    module.exports = exports = mongoose;
    

    然后在您的其他文件中,您可以使用已导出的连接。

    getUsers.js

    const db = require('./db.js');
    const users_collection = await db.collection('users');
    const all_users = await users_collection.find({});
    

    如果您有多个数据库,我建议为每个数据库创建一个连接文件。组织在一个文件夹中。像这样的目录结构

    - package.json
    - <Other files>
    ---| db
    ---|--- users.js
    ---|--- billing.js
    ---|--- <Other Databases>
    

    例如,您将拥有db/users.js

    const mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/users_db');//I would use an environment variable instead of a string for security. 
    module.exports = exports = mongoose;
    

    然后为您的账单db/billing.js

    const mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/billing');//I would use an environment variable instead of a string for security. 
    module.exports = exports = mongoose;
    

    【讨论】:

    • 正是我的想法,但在我观看的课程中,index.js 中只有一个连接,没有任何导出,但他可以直接使用其他路由器文件 (customers.js) 中的数据库,而无需任何要求
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 2019-03-06
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    相关资源
    最近更新 更多