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

如何在JSON数据展示时移除new ObjectId(),直接显示_id字符串值?

MongoDB查询结果去除_id的new ObjectId()包裹方法

你猜测的ObjectId.toString()方法完全可用,只需要在查询拿到结果后、返回数据前手动转换_id字段类型即可,修改后的代码如下:

async get(id) {
    if (!id) throw 'You must provide an id to search for';

    const restaurantsCollection = await restaurants();
    const res = await restaurantsCollection.findOne({ _id: id });
    if (res === null) throw 'No restaurant with that id';

    // 新增这一行,把ObjectId类型转为字符串
    res._id = res._id.toString();
    return res;
}

其他可选方案

  • 如果是批量查询场景,遍历结果数组逐个转换即可:
    const list = await restaurantsCollection.find({}).toArray();
    return list.map(item => {
      item._id = item._id.toString();
      return item;
    });
    
  • 如果希望在数据库查询阶段直接完成转换,可以使用聚合管道的$convert操作符:
    const res = await restaurantsCollection.aggregate([
      { $match: { _id: id } },
      { $addFields: { _id: { $convert: { input: "$_id", to: "string" } } } }
    ]).toArray();
    return res[0];
    
  • 如果你使用的是Mongoose ORM,可以直接在Schema定义阶段配置自动转换,避免每次查询手动处理:
    const restaurantSchema = new mongoose.Schema({
      // 其他字段配置省略
    }, {
      toJSON: { getters: true },
      toObject: { getters: true }
    });
    // 配置_id的getter,自动转为字符串
    restaurantSchema.path('_id').get(v => v.toString());
    

之所以会出现new ObjectId("xxx")的输出形式,是因为MongoDB默认的_id是BSON格式的ObjectId特殊类型,并非原生JavaScript字符串,直接打印或序列化时会展示它的构造函数形式,转为字符串后就会显示为你预期的引号包裹的纯id值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:09:01