Home > Mobile >  Don't store keys with empty string values in mongodb document
Don't store keys with empty string values in mongodb document

Time:07-06

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!

CodePudding user response:

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);
  • Related