Why do we import Mongoose in the Express server file?


I have a Node/Express app that uses Mongoose to talk to a MongoDB database. The Express server is configured in a file called server.js and the schema is in a separate models.js file. Following every project and tutorial I’ve seen so far, I have the mongoose.connect() configured in both places:

// server.js
const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();

// models.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const User = new Schema({
  username: String,
  password: { type: String, select: false },
  name: String,
module.exports = mongoose.model('User', User);

My question is, since I’m already importing mongoose in models.js, can I not skip doing so in server.js entirely and just set the connection in the model script itself? What’s the point of importing it and configuring a connection along with the rest of the server config when I’m only going to use it when working with the schema? And If the answer is yes, why doesn’t anyone do that? Is there a performance benefit at play here?


You could do mongoose.connect() in your model script but this would not be advisable.

You would have to ensure that this model was loaded before any other scripts that required the mongoose connection.

If you go on to create another model in your application, then this would rely on your User model (model.js) having been loaded first.

You would have to perform the connection in each model just to be sure, but this would be a poor design and unnecessary code duplication.

Therefore, connecting in server.js is the best approach to ensure the connection is established as early as possible.

Answered By – Steve Holgado

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published