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
相关产品推荐
相关产品推荐

