How do I add a new Subdocument if it's not exist already, then push another subdocument under it

I have a Schema named user on mongoose, and that schema has lastExams property as below:

lastExams: [{
       lecture:  {
           type: String,
           required: true
       },
       exams: [{
        examID: {type: [mongoose.Schema.Types.ObjectId], ref: Exam, required: true},
        resultID: {type: [mongoose.Schema.Types.ObjectId], ref: Result, required: true},
        date: {type: Date, required: true},
        result: {}
    }]}]

With this, I want to keep the last 10 exams user have taken for each lecture they have. So after each exam, I want to check if the corresponding ‘lastExams.lecture’ subdocument already exists, if so, push the result that lastExams.$.exams array. Else, upsert that subdocument with first element of the exams array.

for example, thats an user document without any exams on it;

  user: {
    name: { firstName: '***', lastName: '***' },
      email: '****@****.***',
      photo: 'https://****.jpg',
      role: 0,
      status: true,
      program: {
        _id: 6017b829c878b5bf117dfb92,
        dID: '***',
        eID: '****',
        pID: '****',
        programName: '****',
        __v: 0
      },
      lectures: [
        {
        some data
        }
      ],
      currentExams: [
         some data
      ],
      lastExams: []
    }}

If user sends an exam data for math-1 lecture, since there is no exam with that lecture name, I need to upsert that document to get user document to become as below;

user: {
  name: {
    firstName: '***',
    lastName: '***'
  },
  email: '****@****.***',
  photo: 'https://****.jpg',
  role: 0,
  status: true,
  program: {
    _id: 6017 b829c878b5bf117dfb92,
    dID: '***',
    eID: '****',
    pID: '****',
    programName: '****',
    __v: 0
  },
  lectures: [{
    some data
  }],
  currentExams: [
    some data
  ],
  lastExams: [{
    lecture: 'math-1',
    exams: [ 
      examID: 601 ba71e62c3d45a4f10f080,
      resultID: '602c09b2148214693694b16c',
      date: 2021 - 02 - 16 T18: 06: 42.559 Z,
      result: {
        corrects: 11,
        wrongs: 9,
        empties: 0,
        net: 8.75,
        score: 43.75,
        qLite: [
         'some question objects' 
        ]
      }
    ]
  }]
}
}

I can do that like this;

 User.findOneAndUpdate({email: result.user}, {$addToSet: {'lastExams': {
                       lecture: result.lecture,
                       exams: [{
                        examID: doc.examID, // btw, idk why, these id's saving to database as arrays
                        resultID: doc.id,
                        date: doc.createdAt,
                        result: doc.results
                      }]
                     }}})

But since this adds new subdoc with same lecture value each time. I am having to check if there is a subdoc with that lecture value first manually. if not so, run the above code, else, to push just exam data to that lectures subdoc, I am using below code;

User.findOneAndUpdate({email: result.user, 'lastExams.lecture': result.lecture }, {$addToSet: {'lastExams.$.exams': {
   examID: doc.examID,
   resultID: doc.id,
   date: doc.createdAt,
   result: doc.results
  }}})

So, I am having to make User.find() query first to see if that lecture is already there, and pop an item if it’s exams.lengt is 10. then deciding to what kind of User.findOneAndUpdate() to use.

Do you think there is any way to make this proccess in a single query? Without going to database 2-3 times for each exam save?

I know it’s too long, but i couldn’t put it straight with my poor english. Sorry.

62 thoughts on “How do I add a new Subdocument if it's not exist already, then push another subdocument under it”

  1. pharmacie annesse et beaulieu medicaments en ligne , therapie de couple grenoble pharmacie des ecoles argenteuil , Comprar Pantosec medicamento, Comprar Pantosec medicamento. Pantosec en farmacia PerГє Comprar Pantosec genГ©rico [url=https://kit.co/raynubbdi/comprar-pantosec-medicamento-pantosec-venta-online#]Comprar Pantosec medicamento, Pantosec venta online[/url] pharmacie saint nicolas angers Mucopain venta online, Comprar Mucopain medicamento. Comprar Mucopain sin receta Comprar Mucopain genГ©rico [url=https://kit.co/gacalgeo/mucopain-en-farmacia-argentina-mucopain-venta-online#]Comprar Mucopain medicamento[/url] , pharmacie de garde marseille quartier nord therapie cognitivo-comportementale gratuite , medicaments anxiete. pharmacie homeopathie argenteuil Comprar Linospan sin receta, DГіnde comprar Linospan antibiotics. Comprar Linospan sin receta Comprar Linospan genГ©rico [url=https://kit.co/koutfaipren/comprar-linospan-generico-comprar-linospan-sin-receta#]Comprar Linospan medicamento[/url] , pharmacie beauvais centre ville huraux therapies alternatives, pharmacie ouverte montauban traitement mycose ongle . therapies for schizophrenia, pharmacie z therapie jeu de sable pharmacie lafayette brest rue de lyon .

    Reply