Skip to content
Advertisement

Don’t store keys with empty string values in mongodb document

i would like to store a post as a document in mongodb. I’m using mongoose for modelling and the content is created by a user using a form. The content of the form is append to FormData and sending to server. This works so far. The only issue is, that empty fields, that are appended as empty strings in the req.body will be stored in the document. The minimalize-property of my dataschema is already set true …

const post = req.body;
await Post.create(post);

req.body looks like:

[Object: null prototype] {
  image: '',
  title: 'hi',
  subtitle: '',
  category: 'Jobs',
  tags: '',
  text: '',
  contactperson: '',
  contact: '',
  author: 'Felicia',
  expires: '2022-08-06'
}

My document looks exactly the same, but i would like to make it look like this:

{
  title: 'hi',
  category: 'Jobs',
  author: 'Felicia',
  expires: '2022-08-06'
}

Thanks so much for your help!

Advertisement

Answer

You could build an object by filtering the req.body empty properties with:

const post = {};
for (const key in req.body) {
    const value = req.body[key];
    if (value && value !== '') {
        post[key] = value
    }
}
await Post.create(post);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement