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

MongoDB中如何将new ObjectId()转换为字符串并正常展示?

解决方法

你当前的get方法仅对餐厅文档顶层的_id做了字符串转换,没有处理嵌套在reviews数组内每条评论的_id字段,所以输出时评论的_id仍然是ObjectId类型,会显示new ObjectId("xxx")的格式。

最简单的修改方案是在get方法返回结果前,遍历reviews数组,将每条评论的_id也转换为字符串即可,修改后的get方法代码如下:

async get(id) {
    if (!id) throw 'You must provide an id to search for';
    checkString(id);
    var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
    if(checkForHexRegExp.test(id)===false) throw 'Not a valid objectid';
    id = ObjectId(id);
    const restaurantsCollection = await restaurants();
    const res= await restaurantsCollection.findOne({ _id: id });
    if (res === null) throw 'No restaurant with that id';
    // 转换餐厅顶层_id为字符串,无需额外正则替换,ObjectId.toString()直接返回24位纯字符串
    res._id = res._id.toString();
    // 遍历处理所有评论的_id
    if (Array.isArray(res.reviews)) {
      res.reviews = res.reviews.map(review => {
        review._id = review._id.toString();
        return review;
      });
    }
    return res;
},

修改后返回的仍然是原生对象结构,所有层级的_id都会展示为纯字符串格式,不会再出现new ObjectId()的包裹内容。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:54:01