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

NestJS中如何解析Mongoose model.findOne()的Pending Promise获取用户对象

解决NestJS中Promise未解析无法获取用户对象的问题

你的核心问题是异步方法调用时未使用await解析Promise,另外代码里还有两处小错误,以下是具体修正方案:

问题分析

  1. findUserByLogin是async方法,直接调用会返回Promise实例而非实际用户对象,必须用await等待Promise解析完成
  2. userIds未初始化就调用push,会触发Cannot read properties of undefined (reading 'push')错误
  3. console.log的变量名写错了,应该是userIds而非userLogins

修正后的代码

private async findUserByLogin(userLogin: string): Promise<Object> {
  const res = await this.userModel.findOne({ login: userLogin }).exec();
  return res;
}

async create(task: Task): Promise<Task> {
  // 初始化数组
  let userIds = [];
  // 使用await解析Promise,获取实际用户对象
  const user = await this.findUserByLogin(task.login);
  userIds.push(user);
  // 修正变量名,输出实际用户数据
  console.log(userIds);
  
  // 补充你的其他业务逻辑,比如创建Task并返回
  // ...
}

额外说明

如果需要批量处理多个用户查询,可以用Promise.all提高效率:

// 假设task.logins是多个登录名的数组
const users = await Promise.all(task.logins.map(login => this.findUserByLogin(login)));
userIds.push(...users);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:22:34