我想在mongodb中存储一个帖子作为一个文档。我使用mongoose建模,内容是由用户使用表单创建的。表单的内容被附加到FormData并发送到服务器。到目前为止,这是可行的。唯一的问题是,空字段,作为空字符串追加到req.body中的将存储在文档中。我的dataschema的minimalize-property已设置为true...
const post = req.body;
await Post.create(post);
请求正文类似于:
[Object: null prototype] {
image: '',
title: 'hi',
subtitle: '',
category: 'Jobs',
tags: '',
text: '',
contactperson: '',
contact: '',
author: 'Felicia',
expires: '2022-08-06'
}
我的文档看起来完全一样,但我想让它看起来像这样:
{
title: 'hi',
category: 'Jobs',
author: 'Felicia',
expires: '2022-08-06'
}
非常感谢你的帮助!
3条答案
按热度按时间cngwdvgl1#
7dl7o3gd2#
您可以将
set
方法用于Mongoose模式:如果字符串等于“”,则将取消设置字段。
使用此选项修剪字符串:
set: (a: string) => a?.trim() === '' ? undefined : a
disbfnqx3#
您可以通过使用以下内容过滤
req.body
空属性来构建对象: