Categories
MongoDB

Using MongoDB with Mongoose — Queries and Aggregations

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.

Cursor Timeout

We can set the noCursorTimeout flag to disable cursor timeout.

For example, we can write:

async function run() {
  const { createConnection, Schema } = require('mongoose');
  const connection = createConnection('mongodb://localhost:27017/test');
  const schema = new Schema({
    name: {
      first: String,
      last: String
    },
    occupation: String
  });
  const Person = connection.model('Person', schema);
  const person = new Person({
    name: {
      first: 'james',
      last: 'smith'
    },
    occupation: 'host'
  })
  await person.save();
  const person2 = new Person({
    name: {
      first: 'jane',
      last: 'smith'
    },
    occupation: 'host'
  })
  await person2.save();
  const cursor = Person.find({ occupation: /host/ })
    .cursor()
    .addCursorFlag('noCursorTimeout', true);
  let doc;
  while (doc = await cursor.next()) {
    console.log(doc);
  }
}
run();

We call the addCursorFlag to disable the cursor timeout.

Aggregation

We can call aggregate to do aggregation with the results.

This will return plain JavaScript objects rather than Mongoose documents.

For example, we can write:

async function run() {
  const { createConnection, Schema } = require('mongoose');
  const connection = createConnection('mongodb://localhost:27017/test');
  const schema = new Schema({
    name: {
      first: String,
      last: String
    },
    occupation: String
  });
  const Person = connection.model('Person', schema);
  const person = new Person({
    name: {
      first: 'james',
      last: 'smith'
    },
    occupation: 'host'
  })
  await person.save();
  const person2 = new Person({
    name: {
      first: 'jane',
      last: 'smith'
    },
    occupation: 'host'
  })
  await person2.save();
  const results = await Person.aggregate([{ $match: { 'name.last': 'smith' } }]);
  for (const r of results) {
    console.log(r);
  }
}
run();

We call aggergate to get all the entries that has the name.last property set to 'smith' .

Then we use a for-of loop to loop through the items since it returns a regular JavaScript array.

The aggregate method doesn’t cast its pipeline, so we have to make sure the values we pass in the pipeline have the correct type.

For instance, if we have:

async function run() {
  const { createConnection, Schema } = require('mongoose');
  const connection = createConnection('mongodb://localhost:27017/test');
  const schema = new Schema({
    name: {
      first: String,
      last: String
    },
    occupation: String
  });
  const Person = connection.model('Person', schema);
  const person = new Person({
    name: {
      first: 'james',
      last: 'smith'
    },
    occupation: 'host'
  })
  await person.save();
  const person2 = new Person({
    name: {
      first: 'jane',
      last: 'smith'
    },
    occupation: 'host'
  })
  await person2.save();
  const doc = await Person.findOne();
  const idString = doc._id.toString();
  const queryRes = await Person.findOne({ _id: idString });
  console.log(queryRes);
}
run();

queryRes isn’t cast to the Person since it’s a plain JavaScript object.

Query Methods

Mongoose comes with the following query methods:

  • Model.deleteMany()
  • Model.deleteOne()
  • Model.find()
  • Model.findById()
  • Model.findByIdAndDelete()
  • Model.findByIdAndRemove()
  • Model.findByIdAndUpdate()
  • Model.findOne()
  • Model.findOneAndDelete()
  • Model.findOneAndRemove()
  • Model.findOneAndReplace()
  • Model.findOneAndUpdate()
  • Model.replaceOne()
  • Model.updateMany()
  • Model.updateOne()

They all return a query object.

Conclusion

We can use Mongoose query methods to query our database.

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 *