You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中MongoDB单语句查询无法获取文档的问题咨询

问题分析:MongoDB查询单语句取最大id报错的原因

在Next.js后端操作MongoDB的users集合时,尝试用单语句获取id最大的用户id:

const max_id = await users.find({}).sort({"id":-1}).limit(1).toArray()[0]["id"]

执行后抛出错误:

unhandledRejection: TypeError: Cannot read properties of undefined (reading 'id')

但拆成两行执行却完全正常:

const newest_user = await users.find({}).sort({"id":-1}).limit(1).toArray();
const max_id = newest_user[0]["id"];

你的猜测不准确,核心问题不是Promise解析时机,而是JavaScript运算符优先级:

  • 成员访问([])的优先级高于await,所以单语句中,代码会先尝试对toArray()返回的Promise对象执行[0]["id"]操作。
  • Promise本身不是数组,用[0]访问会得到undefined,再读取undefined["id"]自然触发TypeError。
  • 分两行执行时,await会先等待Promise解析为数组,再对数组做成员访问,因此不会出错。

内容的提问来源于stack exchange,提问作者Rongeegee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 21:10:40