修改MatchList数据后调用res.json输出未包含更新内容是什么原因?
问题根因
核心原因是异步操作执行顺序错误,Node.js 中所有 MongoDB 数据库操作都属于异步 IO 操作,不会阻塞后续代码执行:
user.save()、matchedUser.save()都是异步方法,调用后不会立刻完成数据持久化,你没有等待这两个操作执行完成,就提前触发了后续的MatchList.findOne({user:userId})查询- 此时数据库中的 matches 字段还未被修改,查询返回的是修改前的旧数据,所以输出中看不到新增的值
- 现有代码嵌套的 Promise 没有做链式处理,也容易出现未捕获的异常,同时没有等待匹配用户的修改操作完成,逻辑上也不严谨。
修复代码示例
将回调逻辑改为 async/await 写法,保证操作按预期顺序执行:
.post(isUser, async (req, res, next) => { try { const userId = req.userId; const matchId = req.body._id; // 修改当前用户的匹配数据 const user = await MatchList.findOne({user: userId}); const idx = user.likes.indexOf(matchId); user.likes.splice(idx, 1); if (user.matches.indexOf(matchId) < 0) { user.matches.push(matchId); } // 等待当前用户数据写入数据库完成 await user.save(); // 修改匹配对象的匹配数据 const matchedUser = await MatchList.findOne({user: matchId}); const matchidx = matchedUser.likes.indexOf(userId); matchedUser.likes.splice(matchidx, 1); if (matchedUser.matches.indexOf(userId) < 0) { matchedUser.matches.push(userId); } // 等待匹配对象数据写入数据库完成 await matchedUser.save(); // 所有修改完成后再查询最新数据返回 const usr = await MatchList.findOne({user: userId}).populate('matches'); res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(usr.matches); } catch (err) { next(err); } })
内容的提问来源于stack exchange,提问作者Abhishek Shah
相关产品推荐
相关产品推荐

