The `db` Property in Mongoose

Jan 21, 2021

Mongoose provides numerous powerful features, like middleware and validation. But sometimes you want to bypass Mongoose and use the MongoDB Node.js driver directly. Mongoose connections have a db property that let you access the MongoDB driver's db handle:

// Connect to a MongoDB server running on 'localhost:27017' and use the
// 'test' database.
await mongoose.connect('mongodb://localhost:27017/test', {
  useNewUrlParser: true // Boilerplate for Mongoose 5.x
});

// Get the current db's profiling level using:
// http://mongodb.github.io/node-mongodb-native/3.6/api/Db.html#profilingLevel
// Mongoose doesn't support getting the profiling level.
const profilingLevel = await mongoose.connection.db.profilingLevel();
profilingLevel; // 'off'

The db property is usually enough, but there are some cases where you need the MongoClient instance instead of the db handle.

// Get another db's profiling level using:
// http://mongodb.github.io/node-mongodb-native/3.6/api/Db.html#profilingLevel
// Mongoose doesn't support getting the profiling level.
const client = mongoose.connection.getClient();
const profilingLevel = await client.db('otherdb').profilingLevel();
profilingLevel; // 'off'

Want to become your team's MongoDB expert? "Mastering Mongoose" distills 8 years of hard-earned lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need to know to build production-ready full-stack apps with Node.js and MongoDB in a few days. Get your copy!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Mongoose Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!