[英]Need to use multiple database in node mongodb/mongoose
好吧,我被困在一些技術性的東西上,讓我解釋一下。
我有一個公司名稱的數據庫,在這個數據庫中有兩列名稱和 DBname,我有多個公司數據庫,現在我想根據公司 DB 調用公司數據。
我已經在我的主要 index.js 中連接了這樣的公司數據庫
const connect = mongoose.connect( 'mongodb://localhost/Company',
{
useNewUrlParser: true, useUnifiedTopology: true,
useCreateIndex: true, useFindAndModify: false
})
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
但我必須根據用戶公司數據庫在用戶登錄時更改此連接
為此,我正在使用這樣的數據庫中間件
const mongoose = require("mongoose");
let DB = (req, res, next) => {
const connect = mongoose.createConnection( 'mongodb://localhost/company_ABC',
{
useNewUrlParser: true, useUnifiedTopology: true,
useCreateIndex: true, useFindAndModify: false
})
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
next();
};
module.exports = { DB };
像這樣,它不起作用請幫助我解決這個問題,並提前致謝
刪除連接字符串后的數據庫名稱。
const connect = mongoose.connect( 'mongodb://localhost/', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }) .then(() => console.log('MongoDB Connected...')) .catch(err => console.log(err));
改為在架構文件中選擇數據庫並將其導出
const mongoose = require('mongoose') const db = mongoose.connection.useDb("company") const collection = db.model('collectionName', collectionSchema); module.exports = { collection };
const { collection } = require('path-to-schema'); const files = await collection.find({})......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.