I have the following code:
JavaScript
x
4
1
Post.create(req.body)
2
.then(post => res.status(201).json(post))
3
.catch(err => res.status(500).json(err))
4
It works perfectly but say I want to exclude a field returned, like the __v field. I know I can do this by just creating an object like
JavaScript
1
5
1
{
2
title: post.title,
3
description: post.description
4
}
5
and etc. for teh other fields, however if I have 20 fields I don’t want to list every single one, so is there a way for mongoose to exclude a field when it returns after it’s created.
Advertisement
Answer
JavaScript
1
4
1
const obj = { a: 1, b: 2, c: 3, d: 4 };
2
(({ b, c, o }) => o)(obj)
3
// returns { a: 1, d: 4 }
4
So, where b
and c
are the keys of the key/value pairs you want left out:
JavaScript
1
4
1
Post.create(req.body)
2
.then(post => res.status(201).json((({ b, c, o }) => o)(post)))
3
.catch(err => res.status(500).json(err))
4
You might have to check the brackets there but I think that’s right.