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

这个Mongoose查询存在什么问题?.then部分执行报错原因排查

问题原因

  • 你混用了await和.then语法,.then回调中执行的forEach没有返回值,导致最终const images拿到的结果是undefined,后续调用images相关属性/方法时就会触发报错。
  • Mongoose的find查询默认返回的是Mongoose Document实例,而非普通JS对象,直接修改实例的自定义属性默认不会生效,也可能触发不可预期的报错。

修复方案

推荐直接使用await+lean()的写法,逻辑更清晰,性能也更好:

// 加lean()直接返回普通JS对象,跳过Mongoose Document封装
const images = await tbl
  .find({
    creator_id: req.user._id,
  })
  .select({
    creator_id: 0,
  })
  .lean();

// 单独遍历处理文件路径
images.forEach((image) => {
  image.file_name = process.env.IMAGE_HOST_URL + image.file_name;
});

如果你要保留.then的写法,必须在回调中返回处理后的数组:

const images = await tbl
  .find({ creator_id: req.user._id })
  .select({ creator_id: 0 })
  .lean()
  .then((images) => {
    images.forEach((image) => {
      image.file_name = process.env.IMAGE_HOST_URL + image.file_name;
    });
    return images; // 必须手动返回处理后的数组
  });

补充说明

如果不想加lean(),修改Mongoose Document属性时需要调用set方法:
image.set('file_name', process.env.IMAGE_HOST_URL + image.file_name)

内容的提问来源于stack exchange,提问作者Bear Bile Farming is Torture

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:39:03