uon-team / db

MongoDB module for @uon/core server applications
MIT License
0 stars 0 forks source link

feature: pushing multiple objects #2

Closed sdalexandre closed 2 years ago

sdalexandre commented 3 years ago

That is maybe already possible but I don't known how, sorry.

For example, if I want to associate multiple students, I must execute the following query for each students:

          await this.dbContext.updateOne(homework, {
              $push: {
                  students: <any>{
                      studentId,
                      addedOn: new Date()
                  }
              }
          });

I already tried with the $each operator, but that give me the following error: unknown top level operator: $each Here is the code I have tried:

            let students: HomeworkStudent[] = [];
            for (let i = 0; i < addStudents.length; i++) {
                students.push(<any>{
                    studentId: addStudents[i],
                    addedOn: new Date()
                });
                wasUpdated = true;
            }

            await this.dbContext.updateOne(homework, {
                $push: {
                    students: {
                        $each: students
                    }
                }
            });
sdalexandre commented 3 years ago

If I do the following instead:

await this.dbContext.updateOne(homework, {
    $push: {
        $each: {
            students
        }
    }
});

it give me the following error in VSCode:

Type '{ $each: { students: HomeworkStudent[]; }; }' is not assignable to type 'ArrayPushOp<ClassroomHomework, Partial<Pick<ClassroomHomework, "students">>>'.
  Object literal may only specify known properties, and '$each' does not exist in type 'ArrayPushOp<ClassroomHomework, Partial<Pick<ClassroomHomework, "students">>>'.ts(2322)
update.interface.d.ts(83, 5): The expected type comes from property '$push' which is declared here on type 'Update<ClassroomHomework>'
uon-io commented 3 years ago

Your first attempt should be correct. I will try to reproduce this error and will advise shortly.

uon-io commented 2 years ago

This is now working properly. The following should work.

await this.dbContext.updateOne(homework, {
    $push: {
        students: {
            $each: students
        }
    }
});

Closing the issue.