1

I have an array called students in a schema called Course. I created a route that allows me to add students to this array using a student's ObjectID like so:

 router.put('/addStudent/:courseID', function (req, res) {
        Course.findOneAndUpdate({courseID: req.params.courseID}, {$push: {students: req.body.students}})
        .populate('students')
        .exec(function (err, course) {

            if (err) return res.status(500).send("There was a problem adding this information to the database");
            res.status(201).send(course);
        })
    });

When I try making a PUT request to my endpoint with the following JSON body:

{
    "students":["5b1f06cafa355c2d187c344f"]
}

Nothing happens at all, it just sends me back the course with the student ID not added. How do I make it so I could add more student IDs to the array? I don't want it to replace the array with a student ID, I want to keep adding more as I make more requests.

Thanks!

Ashh
  • 44,693
  • 14
  • 105
  • 132
sm0keman1
  • 168
  • 1
  • 4
  • 12
  • Put your schema and content in `req.body.students` – Ashh Jun 12 '18 at 07:11
  • That does not make any sense. Adding one ObjectID is fine, but when I try to add another one, it replaces the first ObjectID with the new one when it should be adding. – sm0keman1 Jun 12 '18 at 07:14

3 Answers3

2

put request will update your db and findOneAndUpdate method from mongoose is also for updating you current item, you need to use post request and save method in mongoose instead if you want create a new item.

Emad Dehnavi
  • 3,262
  • 4
  • 19
  • 44
2

You need to use $each with $push

Course.findOneAndUpdate(
  { courseID: req.params.courseID },
  { $push: { students: { $each: req.body.students } } }
)

Course.findOneAndUpdate(
  { courseID: req.params.courseID },
  { $addToSet: { students: { $each: req.body.students } } }
)
Ashh
  • 44,693
  • 14
  • 105
  • 132
0

You can Try this:

Course.findOneAndUpdate(
{ courseID: req.params.courseID }, 
{ $push: {
    students: req.body.students
}}, options, function(err, values){

});
udayakumar
  • 639
  • 1
  • 7
  • 16
  • Does not work, just replaces an id in the array if there is one in there instead of adding to it. – sm0keman1 Jun 12 '18 at 07:10
  • Kindly go through the above edited code. @omar – udayakumar Jun 12 '18 at 07:16
  • Sorry, but I don't seem to understand? The only thing I see difference is the options, but I am not sure what that is? As you can see, my current code does have the $push – sm0keman1 Jun 12 '18 at 07:23
  • You can try the given below link or use the Emad Dehnavi concept http://blog.ocliw.com/2012/11/25/mongoose-add-to-an-existing-array/ – udayakumar Jun 12 '18 at 07:31