MERN应用数据库日期更新无实际变更问题求助
MERN应用数据库更新无实际变更问题排查
问题背景
开发首个MERN应用,已解决更新时的404错误,POST请求返回200状态码,控制台输出“1 Document updated”,但数据库目标文档未发生实际变更,怀疑日期格式问题,寻求排查方向。
相关代码与数据
数据库示例
{"_id":{"$numberInt":"0"}, "name":"Hoya", "waterFrequency":{"$numberInt":"7"}, "waterDate":"2022-09-17"}
后端路由代码
// This section will help you update a record by id. plantRoutes.route("/update/:id").post(function (req, response) { let db_connect = dbo.getDb("plant-babies-data"); let myquery = { _id: ObjectId(req.id) }; let newvalues = { $set: { waterDate: req.body.waterDate }, }; db_connect .collection("plants") .updateOne(myquery, newvalues, function (err, res) { if (err) throw err; console.log("1 document updated"); response.json(res); }); });
前端组件代码
const [updatedPlant, setUpdatedPlant] = useState({ waterDate: "" }); //set useState //calculate new waterDate let date = new Date(); let freq = plant.waterFrequency; date.setDate(date.getDate() + freq) setUpdatedPlant({waterDate:date}) // update database async function submitData(id) { const editedDate = { waterDate: updatedPlant.waterDate }; // This will send a post request to update the data in the database. await fetch(`http://localhost:4000/update/${id}`, { method: "POST", body: JSON.stringify(editedDate), headers: { 'Content-Type': 'application/json' }, }); }
排查步骤
1. 修正文档ID查询的两处错误
- URL参数获取错误:后端用
req.id获取URL中的:id参数是错误的,应该改为req.params.id。当前myquery中的_id值无效,MongoDB找不到匹配文档,但updateOne默认不报错,控制台仍会输出提示(实际0文档更新)。 - ID类型不匹配:数据库中
_id是数字类型($numberInt:"0"),但代码中用ObjectId()转换,导致类型不匹配无法找到文档。需将参数转为数字:let myquery = { _id: parseInt(req.params.id) }; - 同时在回调中打印实际更新数量确认:
console.log(`${res.modifiedCount} document updated`);
2. 统一日期存储格式
数据库中waterDate是YYYY-MM-DD字符串,前端传递的是Date对象,JSON序列化后会变成带时区的ISO字符串(如"2024-05-20T12:34:56.789Z"),可能不符合预期格式。前端计算日期时转为指定格式:
const formattedDate = date.toISOString().split('T')[0]; setUpdatedPlant({waterDate: formattedDate});
3. 验证前后端参数传递
- 前端
submitData中打印editedDate,确认waterDate值是否正确; - 后端路由中添加日志,确认参数接收情况:
console.log("Received id:", req.params.id); console.log("Received waterDate:", req.body.waterDate);
4. 查看MongoDB更新操作的真实结果
updateOne返回的res包含matchedCount(匹配文档数)和modifiedCount(实际更新数),打印这两个值能明确是否找到文档及是否完成更新:
console.log(`匹配${res.matchedCount}个文档,更新${res.modifiedCount}个文档`);
内容的提问来源于stack exchange,提问作者Allyson Smith
相关产品推荐
相关产品推荐

