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
You could build an object by filtering the
req.body
empty properties with:You could use the
set
method for Mongoose Schemas:This will unset the field if the string equals ”.
Use this to trim the strings:
set: (a: string) => a?.trim() === '' ? undefined : a