Search code examples
mongoose

Difference between connection, client and db in Mongoose


I am creating a connection to a database in mongoose as follows

// CONNECTION to Mongo without database name. Eg DATABASE_URL=mongodb://0.0.0.0:27017/
const connection = await mongoose.connect(process.env.DATABASE_URL);

// GET CLIENT
var dbClient = connection.connections[0].client;
    
// GET DATABASE. Eg. DATABASE=Questions
db = dbClient.db(process.env.DATABASE);

What is the difference between connection, dbClient. I think I understand that database represents?

If I create a model and call save on it, how do I tell mongoose to save in a collection in DATABASE?

const Question = mongoose.model("Question", questionSchema);
module.exports = Question;

...

q = Question({
  description: "some description",
  hints: ["hint1", "hint2"],
  topic: 'area'
});

await q.save()

Solution

  • The power of mongoose is that a lot is done for you. You don't ever need to access the database, connection, nor the dbClient.

    By doing await q.save(), you already tell mongoose to save the q document you created.

    And it knows where to save it because you declared Question as a model with a schema:

    mongoose.model("Question", questionSchema)
    

    At startup, mongoose should have created the Question collection for you.

    You should see this collection with 1 document appear in MongoDB Compass.


    Update: I think you are mixing databases and collections.

    One database should be per environment, like prod, staging, dev, etc.

    Accessing multiple databases in the same application is a dark pattern. The connection string should contain the database, and be an environment variable:

    DATABASE_URL=mongodb://0.0.0.0:27017/<your-database-name>
    

    Generally, databases are named <application-name>-<environment>.

    If you have multiple types of questions, you should create multiple collections in your database:

    • Database: <application-name>-<environment>
      • Collection 1: questions-areas
      • Collection 2: questions-<name 2>, etc.