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

使用Mongoose添加的文档未在MongoDB Compass中显示

使用Mongoose创建文档返回成功,但MongoDB Compass中找不到数据

我通过Mongoose的create方法添加产品文档,接口返回成功响应,请求体数据正常,但在MongoDB Compass中无法找到对应的文档。已检查DB_URL等配置,未发现问题。

相关代码(productController.js)

exports.createProduct = async (req, res, next) => {
  try {
    console.log("Request Body:", req.body); // Log the request body for debugging
    const product = await Product.create(req.body);

    res.status(201).json({
      success: true,
      product,
    });
  } catch (error) {
    console.error("Error creating product:", error);
    res.status(400).json({
      success: false,
      message: error.message,
    });
  }
};

打印的请求体

Request Body: {
name: 'Vaseline petrolatum Jelly',
description: 'Simple product.',
price: 100,
rating: 3,
category: 'Health',
images: { public_id: 'sample public id', url: 'sample url' }
}

排查方案

  • 核对集合名称:Mongoose默认会将模型名转为复数小写作为集合名(如Product模型对应products集合),确认你在Compass中查看的是正确的集合。
  • 确认连接的数据库:在数据库连接成功后添加日志,打印mongoose.connection.name,验证当前连接的数据库与Compass中打开的是否一致。
  • 检查Schema约束:若Product Schema存在必填字段未设置、字段类型不匹配等情况,Mongoose默认(strict: true)会静默丢弃不符合的数据。可以开启Mongoose调试模式查看实际操作:
    mongoose.set('debug', true);
    
    同时核对Schema定义,确保请求体中的字段都符合要求。
  • 排查事务提交情况:如果代码中使用了事务但未提交,文档不会写入数据库,检查是否有未完成的事务逻辑。
  • 刷新Compass并检查过滤条件:手动刷新Compass界面,确认没有设置错误的过滤规则导致数据被隐藏。
  • 检查软删除逻辑:若项目实现了软删除(如isDeleted字段),文档可能存在但被过滤,检查Schema和业务代码中是否有相关处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:07:16