Mongoose Compound Indexes | Helpfulz

Mongoose Compound Indexes

May 30, 2020

After googling around i found a solution to a pretty tricky but neat problem i had.

I wanted to be able to create a schema that would ensure a combination of two or more indexes were unique.

I also wanted the route to either create a new one if the unique combination was not there, or just return the document if it already existed, and i did this with the help of stack overflow

So here is my model. I’ve initiated the Schema like i normally do, but I added a line afterwords that makes the combination of invitee and eventId unique. So the combination needs to be unique, not necessarily one or the other.

// Model.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const inviteSchema = new Schema(
    invitee: { type: String },
    eventId: { type: String },

inviteSchema.index({ invitee: 1, eventId: 1, }, { unique: true })

const Invite = mongoose.model("Invite", inviteSchema);

module.exports = Invite;

Getting into the weeds on this if your interested: According to their docs you can define indexes at the path level or the schema level. In order to do these compound indexes it is required to do that using the schema level. This is why i needed that inviteSchema.index(…) line of code.

Now to the controller:

const db = require("../models");

// Defining methods for the InvitesController
module.exports = {
  create: function(req, res) {
    const options = { upsert: true, new: true, setDefaultsOnInsert: true };
      .findOneAndUpdate(req.body, req.body, options)
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));

So this function allows me to simply return the document if the combination of the “invitee” and “eventId” keys are not unique, and create a new document if the combination is unique.

Profile picture

Written by IzzleNizzle who can be found playing around in the mountains of Utah. ⛰️ You should follow Iz on Twitter

© 2022, Built with Gatsby and WordPress