【发布时间】:2019-06-10 22:27:05
【问题描述】:
我无法更新 mongodb 文档中的数组(即使我一直得到状态 200)。这是来自 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 }
我需要在数组"time" 中添加一些数字。在浏览了 stackoverflow 一段时间后,我没有找到任何可以编写查询的解决方案,mongoose 可以为我验证数据,所以我想出了这个临时代码
updateEventHeight(id) {
let updates = `{\"time\": [6, 7, 8]}`;
let newId = `{\"_id\" : ${id}}`;
this.props.updateEvent(newId, updates);
}
在我的父 React 组件中,我正在拨打axios 电话
axios.post("/api/updateEvent", {
id: id,
update: updates
})
在服务器端我有 Express.js 处理更新请求,响应到 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 });
});
});
服务器控制台日志带有响应 200。但数据没有持久保存到数据库中。
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 - -
【问题讨论】:
标签: node.js reactjs mongodb express