0

I am currently trying to build a simple REST API through Heroku to manage a database of teachers and their ratings for a app I'm developing for my Computer Science course. The front end is going to be written in React, but that isn't important yet. I am having issues with pushing reviews into a teacher's array of reviews. My teacher object looks like this:

"_id": {

    "$oid": "59f3662142c2480012d2d5f6"
},
"name": "Matt Albinson",
"subject": "Computer Science",
"createDate": {
    "$date": "2017-10-27T17:00:17.908Z"
},
"roasts": [
    {
        "rating": 5,
        "review": "He's Alright"
    }
]

I want to be able to add another review to a teacher and to delete specific reviews from a teacher's array of reviews. Below is the code I am using that currently is not working.

app.post("/api/teachers/:id", function(req, res) {

  var updateDoc = req.body;

  db.collection(TEACHERS_COLLECTION).updateOne({ roasts: new ObjectID(req.params.roasts)}, updateDoc, function(err, doc) {

    if (err) {
      handleError(res, err.message, "Failed to update teacher");
    } else {
      updateDoc.roasts = req.params.roasts;
      res.status(200).json(updateDoc);
    }
  });
});

Edit: This is not the same question as that duplicate since that is a general mongo question. I am writing a node.js RestAPI using Mongo and need solutions for that specific use case. I am really just unsure how to add new items to my roasts array when I am posting to the url including the teacher's ID. I would be find posting to the general teacher list, but I can't seem to get past my teacher creation method.

  • What is the value of `TEACHERS_COLLECTION`? Also, you're specifying `roasts` which should be `_id`? What's the value of `req.params.roasts` - is that the ObjectId value? Not enough info here. – dzm Nov 06 '17 at 19:54
  • Ignore the "mongoose" part in the linked question. What you want is [`$push`](https://docs.mongodb.com/manual/reference/operator/update/push/) to add array items and [`$pull`](https://docs.mongodb.com/manual/reference/operator/update/push/) to remove. You probably should be reading all of [MongoDB CRUD Operations](https://docs.mongodb.com/manual/crud/) to get acquainted with these operations in general. Also note that `updateOne()` without using any of these [update operators](https://docs.mongodb.com/manual/reference/operator/update/) actually "replaces" the document, implying `replaceOne()` – Neil Lunn Nov 07 '17 at 00:45

0 Answers0