NodeJS/Express遍历元素执行Mongoose查询时异步操作异常问题
问题解决方法
你的问题核心是Mongoose的数据库查询是异步操作,同步执行的next()不会等待异步查询的回调执行完成就会触发,我们可以通过async/await配合Promise控制异步执行顺序解决这个问题。
改造后的代码实现
// 注意:需要先给当前的路由处理函数添加async关键字,示例: // router.post('/save-contacts', async (req, res, next) => { try { // 批量生成所有联系人的查询Promise const checkTasks = req.body.contacts.map(contact => Contact.findOne({ contact_name: contact.contact_name, phone: contact.phone, user_id: req.userId }) ) // 等待所有查询任务执行完成 const checkResults = await Promise.all(checkTasks) // 判断是否存在重复联系人 const hasDuplicate = checkResults.some(item => item !== null) if (hasDuplicate) { // 409状态码更符合资源冲突的业务场景 return res.status(409).send({ message: "You have already submitted this contact" }) } // 所有校验通过后再调用next() next() } catch (err) { console.log(err) res.status(500).send({ message: "Server error occurred while checking contacts" }) }
方案说明
- 用
findOne替代原有的find查询,性能更高,只要匹配到一条记录就会返回,无需拉取所有匹配结果 Promise.all会等待所有异步查询执行完成后才会往下执行代码,保证校验逻辑全部完成后才调用next()- 统一在所有查询结束后判断是否有重复,避免原写法中多个查询回调同时触发
res.send导致的响应头重复设置报错 - 用
try/catch统一捕获所有查询过程的异常,逻辑更简洁
可选优化方案
如果联系人数组长度不大,希望只要查到一个重复就立刻返回,不需要等所有查询完成,可以用串行查询的写法:
try { for (const contact of req.body.contacts) { const exists = await Contact.findOne({ contact_name: contact.contact_name, phone: contact.phone, user_id: req.userId }) if (exists) { return res.status(409).send({ message: "You have already submitted this contact" }) } } next() } catch (err) { console.log(err) res.status(500).send({ message: "Server error occurred while checking contacts" }) }
内容的提问来源于stack exchange,提问作者Zuss
相关产品推荐
相关产品推荐

