Skip to content

How to exclude fields on return in mongoose

I have the following code:

.then(post => res.status(201).json(post))
.catch(err => res.status(500).json(err))

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

  title: post.title,
  description: post.description

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.


const obj = { a: 1, b: 2, c: 3, d: 4 };
(({ b, c, ...o }) => o)(obj)
// returns { a: 1, d: 4 }

So, where b and c are the keys of the key/value pairs you want left out:

  .then(post => res.status(201).json((({ b, c, ...o }) => o)(post)))
  .catch(err => res.status(500).json(err))

You might have to check the brackets there but I think that’s right.