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

初始化profile集合后首次调用find返回空数组的问题咨询

问题根因

你遇到的问题和集合有没有预初始化没有任何关系,完全是异步操作没加等待导致的:profile.save()是异步方法,你当前的代码没有加await等待它写入数据库完成,就直接执行了Profile.find()查询。首次调用时,查询动作比写入动作先完成,自然返回空数组;第二次调用时第一次的写入已经落地,所以查询会返回前后两次写入的两条记录。

修复方案

不需要在用户注册时预创建集合,MongoDB会在你首次写入文档时自动生成对应的集合,直接修改接口逻辑即可:

  1. 给profile.save()加上await,等待写入完成再执行查询
  2. 建议把写入操作也移入try catch块内,统一捕获异常,写法更严谨

修复后的代码如下:

// 新增profile接口
router.post("/", async (req, res) => {
  try {
    const profile = new Profile({
      name: req.body.name,
      picture: req.body.picture,
    });
    // 等待写入数据库完成
    await profile.save();
    const allProfiles = await Profile.find();
    console.log(allProfiles);
    res.status(200).json({ success: "Profile added", profiles: allProfiles });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:06:03