rob111
rob111

Reputation: 1257

Couldn't Update array in MongoDB with mongoose

I couldn't update an array in mongodb document (even I am getting status 200 all the time). Here is document from mongoDB

{ "_id" : ObjectId("5c3f3a59bdbd208298139e23"), "time" : [ 6 ], "id" : 4, "date" : 1547388300000, "text" : "New nEw neW event", "createdAt" : ISODate("2019-01-16T14:06:17.688Z"), "updatedAt" : ISODate("2019-01-16T14:06:17.688Z"), "__v" : 0 }

I need to add some numbers to an array "time". After browsing stackoverflow for some time I didn't find any solution where I can write query which mongoose can validate the data for me so I came up with this temporary code

updateEventHeight(id) {
    let updates = `{\"time\": [6, 7, 8]}`;
    let newId = `{\"_id\" : ${id}}`;
    this.props.updateEvent(newId, updates);
  }

In my parent React component I am making axios call

axios.post("/api/updateEvent", {
      id: id,
      update: updates
    })

And on server side I have Express.js which handles update request, response into MongoDB

router.post("/updateEvent", (req, res) => {
  const { id, update } = req.body;
  Data.findOneAndUpdate(id, update, err => {
    console.log(id);
    console.log(update);
    if(err) return res.json({ success: false, error: err });
    return res.json({ success: true });
  });
});

Server console log comes with response 200. But data didn't persist into DB.

GET /api/getEvents 304 4.579 ms - -
[0] GET /api/getEvents 304 4.590 ms - -
[0] {"_id" : 5c3f3a59bdbd208298139e23}
[0] {"time": [6, 7, 8]}
[0] POST /api/updateEvent 200 8.166 ms - 162
[0] GET /api/getEvents 304 3.318 ms - -
[0] GET /api/getEvents 304 3.316 ms - -

Upvotes: 0

Views: 858

Answers (1)

Dadsquatch
Dadsquatch

Reputation: 566

Here is a sample of my code that works for finding a Project and adding in additional notes into the array.

   Data.findOneAndUpdate(
      { _id: req.body._id },
      {
        $push: {
          time: req.body.value
        },
        new: true
      }
    )
      .then(doc => {
        res.send(doc);
      })
      .catch(err => {
        console.error(err);
      });
  });

You may also want to look into $pushAll if you are handling multiple values going into the array as well as $each they have different uses, but might help you. The way I have shown here is for just pushing a new value onto an array that already exists in the database.

Upvotes: 1

Related Questions