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!

2
  • Put your schema and content in req.body.students Commented Jun 12, 2018 at 7: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. Commented Jun 12, 2018 at 7:14

3 Answers 3

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 } } }
)
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Can you please provide an example?
0

You can Try this:

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

});

4 Comments

Does not work, just replaces an id in the array if there is one in there instead of adding to it.
Kindly go through the above edited code. @omar
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
You can try the given below link or use the Emad Dehnavi concept blog.ocliw.com/2012/11/25/mongoose-add-to-an-existing-array

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.