Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

Mongoose increment nested array by id


This is my model:

const mongoose = require("mongoose");
const shortid = require("shortid");
const { v4: uuidv4 } = require("uuid");

const PollSchema = new mongoose.Schema({
  id: {
    type: String,
    default: shortid.generate
  },
  question: {
    type: String
  },
  options: [
    {
      option: {
        type: String
      },
      votes: {
        type: Number,
        default: 0
      },
      uid: {
        type: String,
        default: uuidv4
      }
    }
  ],
  created: {
    type: Date,
    default: Date.now
  }
});

module.exports = Poll = mongoose.model("poll", PollSchema);

I need to search for the poll by uid and increment the votes number by 1. This is what I've tried and it doesnt work:

Poll.findOneAndUpdate(
  { options: { $elemMatch: { uid: optionId } } },
  { $inc: { "options.$.votes": 1 } },
  { new: true }
);

nothing updates in the database I'm not sure why. The var of the search uid that I supply is optionId.


Solution

  • For 1 Level nesting its not necessary to use arrayFilters so this should work:

    Poll.findOneAndUpdate({ _id: yourId, "options.uid": optionId }, { $inc: { "options.$.votes": 1 }, { new: true } })