0

I am trying to integrate the following packages to create an API that saves files into MongoDB. mongodb, multer, multer-gridfs-storage, gridfs-stream.

(I am using mongodb driver and not mongoose)

I've used the following code to establish the connection, create the grid, and export the db instance:

import { MongoClient, Db, MongoError } from "mongodb";
import Grid from "gridfs-stream";

let db: Db;
let gfs: Grid.Grid;

export const connectToDb = (cb: Function) => {
    MongoClient.connect(process.env.MONGODB_CONNECTION_STRING!)
        .then((client) => {
            db = client.db("main-database");
            gfs = Grid(db, MongoClient);
            gfs.collection("uploads");
            return cb();
        })
        .catch((err: MongoError) => {
            console.error(err);
            return cb(err);
        });
};

export const getDb = () => db;

It works fine so far as in it actually saves files to the atlas cluster.

Where it behaves unexpectedly is when it creates a separate database in the cluster called "test" rather than the one I specified ("main-database"). And now I end up with two databases in my cluster, "main-database" with the collections I specify, and "test" with the gridfs collections "uploads.chunks" and "uploads.files". What I want is all my collections under one database ("main-database").

Any idea why this is happening and how to fix it?

Swordax
  • 3
  • 1
  • 1

0 Answers0