Home > Software engineering >  Mongoose how to add a key:value to an existing object
Mongoose how to add a key:value to an existing object

Time:12-22

I am trying to add a manual index value into my existing collection, due to change of plans on some things.

my schema is the following:

const quizzerSchema = mongoose.Schema(
  {
    title: {
      type: String,
    },
    imgUrl: {
      type: String,
    },
    SKU: {
      type: String,
    },
    topics: [
      {
        topicTitle: { type: String },
        index: { type: Number }, //NEW VALUE TO ADD
        questions: [
          {
            section: { type: String },
            setup: { type: String },
            question: { type: String },
            correct: { type: String },
            answer: { type: String },
            note: { type: String },
            questionNumber: { type: String },
            a: { type: String },
            b: { type: String },
            c: { type: String },
            d: { type: String },
            e: { type: String },
            i: { type: String },
            ii: { type: String },
            iii: { type: String },
            iv: { type: String },
            v: { type: String },
            vi: { type: String },
            vii: { type: String },
            viii: { type: String },
            ix: { type: String },
            x: { type: String },
            hasFactPattern: { type: Boolean },
            index: { type: Number }, //NEW VALUE TO ADD
          },
        ],
      },
    ],
  },
  {
    timestamps: true,
  }
);

I want to be able to just run a function once to add the index key and loop through it to add an index number, so I don't have to do it all manual.

This is the function i have:

const book = await Quizzer.findById(bookid);

  for (let i = 0; i < book.topics.length; i  ) {
    await Quizzer.updateOne({ _id: bookid }, { $set: { "book.index": i } });
  }

But it not doing anything. Any help would be appreciated

Thank you all

CodePudding user response:

This should work:

const book = await test.findById(id);

for (let i = 0; i < book.topics.length; i  ) {
    book.topics[i].index = i
}
await book.save()

There is probably a better way though, im still learning mongoose so this is the best i can do.

  • Related