skip to Main Content

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!

3

Answers


  1. 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);
    
    Login or Signup to reply.
  2. let post = {
      image: '',
      title: 'hi',
      subtitle: '',
      category: 'Jobs',
      tags: undefined,
      text: null,
      contactperson: '',
      contact: '',
      author: 'Felicia',
      expires: '2022-08-06'
    };
    let payload ={}
    Object.keys(post).filter((key) => !!post[key] && (payload[key] = post[key]));
    console.log(payload)
    Login or Signup to reply.
  3. You could use the set method for Mongoose Schemas:

    const mySchema = new mongoose.Schema(
      {
        myAttribute: {
          type: String,
          set: (attribute: string) => attribute === '' ? undefined : attribute,
        },
      },
      { strict: 'throw' },
    );
    

    This will unset the field if the string equals ”.

    Use this to trim the strings:
    set: (a: string) => a?.trim() === '' ? undefined : a

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search