Mongoose add or update values in an array inside an object inside an array

Viewed 28

This is my schema,

const courseSchema = new mongoose.Schema({
  name: String,
  code: String,
  class: String,
  credit: Number,
  overview: String,
  prerequisite: String,
  syllabus: [
    {
      moduleName: String,
      moduleDetails: String,
    },
  ],
  materials: [
    {
      moduleNo: Number,
      moduleMaterials: [String],
    },
  ],
  teacher: String,
  students: [String],
});

I want to add new materials in which each time an update operation is called I receive a moduleNo and a materialURL. I want to add this to the materials array in my existing course which is filtered by courseID. So each time I receive a moduleNo and a materialURL, I want to check if moduleNo already exists in the materials array. If yes, then add materialURL into the moduleMaterials array without deleting the existing urls in moduleMaterials. If no, then add a new object with moduleNo and moduleMaterials and materialURL pushed into moduleMaterials. I've heard about upsert and think that could be used but I'm not sure what the correct queries are to do this operation. What I've currently come up with even though it's wrong,

  Course.updateOne(
    { _id: courseID },
    {
      $push: {
        materials: { moduleNo, moduleMaterials: { $push: { materialURL } } },
      },
    },
    { upsert: true },
    (err, result) => {
      if (err) {
        console.error(err);
      } else {
        console.log(result);
      }
    }
  );

How do I do execute this query?

0 Answers
Related