0

my application tracking student enrollment to different courses.

the schema is:

const userSchema = new mongoose.Schema({

    username: String,
    password: Number,
    enrollment: []

})

and the enrollment array looks like this:

[{courseName: somename, courseTime:sometime},{courseName: somename2, courseTime:sometime2}]

the student can supply information whether he was attend at specific date on the course meeting or not.

so the thing I want to do is:

a) find the specific student b) find the the specific course of this student c) add to the object that contains this course additional object that contain date field and yes/no field.

so i wont it looks something like this:

[{courseName: somename, courseTime:sometime, newObject:{date:someDate, attendance:true}},{courseName: somename2, courseTime:sometime2,newObject:{date:someDate2, attendance:false}}]

I found similar questions in topics like this: update Object inside array of Object with mongoose or update Object inside array of Object with mongoose

and its not seems like a very hard task, but the problem is that I probably missing some simple syntax rules, because when I type this code into VScode I see picture like this:

error

any help would be much appreciated

1 Answer 1

0

Here's one way to update "enrollment" and add "newObject".

db.collection.update({
  "username": "john1234" // from req.body.username
},
{
  "$set": {
    "enrollment.$[course].newObject": {
      // from req.body.xxx
      "date": ISODate("2022-12-01T09:00:00Z"),
      "attendance": true
    }
  }
},
{
  "arrayFilters": [
    { // from req.body.courseName
      "course.courseName": "NIE-SW101"
    }
  ]
})

Example output:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "enrollment": [
      {
        "courseName": "NIE-SW101",
        "courseTime": ISODate("2022-12-01T09:00:00Z"),
        "newObject": {
          "attendance": true,
          "date": ISODate("2022-12-01T09:00:00Z")
        }
      },
      {
        "courseName": "NIE-HI101",
        "courseTime": ISODate("2022-12-05T15:00:00Z")
      }
    ],
    "password": 1234,
    "username": "john1234"
  }
]

Try it on mongoplayground.net.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.