Categories
MongoDB

Using MongoDB with Mongoose — Connections

Spread the love

To make MongoDB database manipulation easy, we can use the Mongoose NPM package to make working with MongoDB databases easier.

In this article, we’ll look at how to use Mongoose to manipulate our MongoDB database.

Connections

We can connect to a MongoDB database with Mongoose.

To do that, we write:

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017/test";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

We connect to the server with the URL and the test collection name.

Operation Buffering

We can start using the models immediately without waiting fir Mongoose to establish a connection.

So we can write:

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017/test";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

async function run() {
  const Assignment = mongoose.model('Assignment', { dueDate: Date });
  const assignment = new Assignment({ dueDate: new Date() });
  await assignment.save();
  Assignment.findOne((err, doc) => {
    doc.dueDate.setMonth(3);
    doc.save();
    doc.markModified('dueDate');
    doc.save();
  })
}
run();

We create our model and use it without waiting for the connect to complete since we have the database code outside the callback.

This is because Mongoose buffers the model function calls internally.

However, Mongoose won’t throw any errors if we use models without connecting.

We can disable buffering by setting bufferCommands to false :

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017/test";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
mongoose.set('bufferCommands', false);
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

We can create collections with the createCollection method:

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017/test";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

async function run() {
  const schema = new mongoose.Schema({
    name: String
  }, {
    capped: { size: 1024 },
    bufferCommands: false,
    autoCreate: false
  });

  const Model = mongoose.model('Test', schema);
  await Model.createCollection();
}
run();

Now we’ll create the tests collection to create the collection.

Error Handling

We can catch any errors that are raised with the catch method or try-catch with async and await since mongoose.connect returns a promise.

For example, we can write:

const mongoose = require('mongoose');
async function run() {
  try {
    await mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
  } catch (error) {
    handleError(error);
  }
}
run();

or:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true }).
  catch(error => handleError(error));

to connect to a database.

We can also listen to the error event as we did in the example above.

Callback

The mongoose.connect method takes a callback to so we can check for errors.

For example, we can write:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true }, function (error) {
  console.log(error);
})

Connection String Options

We can add connection options to the connection string.

For example, we can write:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test?connectTimeoutMS=1000&bufferCommands=false')

We set the connection timeout with the connectTimeoutMS option is set to 1000ms to set.

And we also set bufferCommands option to false .

Conclusion

There are many things we can configure with connections.

Also, Mongoose buffers any commands queued before the connection is made by default so we don’t have to wait for a connection is done before running Mongoose methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *