在显示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("(.*)")/, "$1")
return res;
}
res._id = res._id.str;
return res;
https://docs.mongodb.com/manual/reference/method/ObjectId/
当从MongoDb接收字符串数组时,我遇到了类似的问题(由于后端抽象逻辑,有必要在没有解析的情况下发送它)。
在我的情况下,我有很多对象在这个字符串数组与ObjectId作为id道具的值,例如:
"[{'id': ObjectId(id)}, // many others]"
我的解决方案是写一个递归函数来获取每个'ObjectId'字符串的索引,然后使用JS子字符串方法删除它。
我把它留在这里供参考,以防有人需要。
function removeObjId(str){
const objIdLen = 9;
const objIdInd = str.search("ObjectId");
if(objIdInd == -1) return str;
const objIdEndInd = objIdInd + objIdLen
const valueInd = str.substring(objIdEndInd)
const commaInd = valueInd.indexOf(",")
const nStr =
str.substring(-1, ind-1)
+ "'"
+ str.substring(objIdEndInd, objIdEndInd + commaInd -1)
+ "'"
+ str.substring(commaInd + objIdEndInd)
return removeObjId(nStr)}