如何从 JSON 数据的显示中删除 new ObjectId()?

How to remove new ObjectId() from the display of JSON data?

如何在显示 JSON 数据时从我的输出中删除新的 ObjectId()?

下面是我使用来自 mongodb 的 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';

    return res;

输出为:

{
  _id: new ObjectId("6157530bbba1dbb9f7e68e4a"),
  name: 'The Saffron Lounge',
  location: 'New York City, New York',
  phoneNumber: '123-456-7890',
  website: 'http://www.saffronlounge.com',
  priceRange: '$$$$',
  cuisines: [ 'Cuban', 'Italian' ],
  overallRating: 3,
  serviceOptions: { dineIn: true, takeOut: true, delivery: false }
}

我想要的输出是:

{
  _id: "6157530bbba1dbb9f7e68e4a",
  name: 'The Saffron Lounge',
  location: 'New York City, New York',
  phoneNumber: '123-456-7890',
  website: 'http://www.saffronlounge.com',
  priceRange: '$$$$',
  cuisines: [ 'Cuban', 'Italian' ],
  overallRating: 3,
  serviceOptions: { dineIn: true, takeOut: true, delivery: false }
}

我使用 ObjectId.toString() 吗?也不知道在哪里使用它

根据这个 https://docs.mongodb.com/manual/reference/method/ObjectId.toString/ ObjectId.toString() 会给你一个仍然包含 ObjectId("...") 部分的字符串。您可以使用正则表达式将其删除。

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';
    res._id = res._id.toString().replace(/ObjectId\("(.*)"\)/, "")
    return res;
    
 }

res._id = res._id.str;
return res;

https://docs.mongodb.com/manual/reference/method/ObjectId/