Reputation: 2305
I want to remove properties _id
and __v
from Mongo result (which is array with markers) with map, but I always get array with null
values in JSON result instead of array with objects without this two properties.
Marker.find().then(result => {
const markers = result.map(marker => {
delete marker['_id'];
delete marker['__v'];
});
res.send(JSON.stringify({ markers: markers }));
}).catch(next);
This is how returned JSON looks without mapping:
{
"markers": [
{
"_id": "5a7e266b6d7f6d00147bc269",
"id": "da27cbf8372aaeb24ce20a21",
"x": "25",
"y": "37",
"timestamp": 2093355239,
"__v": 0
},
{
"_id": "5a7e2789c61cf90014d67e6b",
"id": "5580d237f486088499c6d82k",
"x": "56",
"y": "29",
"timestamp": 2138203308,
"__v": 0
},
]
}
This is how returned JSON looks with mapping:
{
"markers": [
null,
null
]
}
Upvotes: 0
Views: 464
Reputation: 2305
Problem is solved. None of given solutions have worked because the problem was about Mongoose. Data returned by Mongoose is MongooseDocument
and is not editable. I just had to add lean()
method in query to get the editable result. After that, I used Icepickle's solution.
Marker.find().lean().then(result => {
const markers = result.map(marker => {
const { ['_id']: _, ['__v']: __, ...rest } = marker;
return rest;
});
res.send(JSON.stringify({ markers: markers }));
}).catch(next);
Upvotes: 0
Reputation: 22876
Key value pairs can be filtered in the JSON.stringify
replacer parameter :
o = {"markers":[{"_id":"5a7e266b6d7f6d00147bc269","id":"da27cbf8372aaeb24ce20a21","x":"25","y":"37","timestamp":2093355239,"__v":0},{"_id":"5a7e2789c61cf90014d67e6b","id":"5580d237f486088499c6d82k","x":"56","y":"29","timestamp":2138203308,"__v":0}]}
j = JSON.stringify(o, (k, v) => k[0] === '_' ? void 0 : v, 2)
console.log(j)
Upvotes: 0
Reputation: 12796
Instead of deleting (and essentially mutating your result array), you could consider the following
Marker.find().then(result => {
const markers = result.map(marker => {
const { ['_id']: _, ['__v']: __, ...rest } = marker;
return rest;
});
res.send(JSON.stringify({ markers: markers }));
}).catch(next);
which would use destructuring to create a copy of the marker, ommitting the 2 properties that you have previously deleted. So _
would contain the value for _id
and __
would contain the value for __V
, the remaining part of your object would be contained inside the rest
variable
Upvotes: 1
Reputation: 60466
You need to return something in your map function. The map function returns a new array containing what you return from your map function. If you return nothing it is undefined.
Marker.find().then(result => {
const markers = result.map(marker => {
delete marker['_id'];
delete marker['__v'];
return marker;
});
res.send(JSON.stringify({ markers: markers }));
}).catch(next);
Upvotes: 2