When I get data from mongo via mongoose with...
const allAssets = await assets
.find({ company })
.sort([['createdAt', -1]])
.exec();
res.status(200).json({ assets: allAssets });
I always get _id and __v but I dont want to send these to the front end, is there a way I can easly say I dont want these values or remove them before sending them?
{
"indistructable": true,
"_id": "5e345c2dc84be8995a5b4cf2",
"baseUri": "https://api.website.com/nameco8/",
"company": "jnameco8",
"description": "asset",
"image": "myimage.png",
"name": "jim",
"supply": 100,
"createdAt": "2020-01-31T16:56:13.816Z",
"updatedAt": "2020-01-31T16:56:13.816Z",
"__v": 0
},
I have tried adding
__v: {type: Number, select: false},
_id: { type: mongoose.Schema.Types.ObjectId, select: false },
to my schema but when saving to the schema I then get an error
"document must have an _id before saving"
As far as I believe schemas are for writes to restrict unknown fields from being written to documents which make your documents look similar across your collection, but if you need to remove few fields in read then try projection in .find() :
const allAssets = await assets
.find({ company }, {_id :0, __v:0})
.sort([['createdAt', -1]])
.exec();
res.status(200).json({ assets: allAssets });