简体   繁体   中英

How to exclude fields on return in mongoose

I have the following code:

Post.create(req.body)
.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:

Post.create(req.body)
  .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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM