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 - -