不要在mongodb文档中使用空字符串值的商店键
我想在MongoDB中存储一个文档。我正在使用Mongoose进行建模,并且内容由用户使用表单创建。表单的内容附加到FormData并发送到服务器。到目前为止,这起作用了。唯一的问题是,在reqbody中将其附加为空字符串的空字段将存储在文档中。最小化我的dataschema的范围已经设置为真……
const post = req.body;
await Post.create(post);
req.body看起来像:
[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'
}
非常感谢您的帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过过滤
req.body
 空属性来构建对象。You could build an object by filtering the
req.body
empty properties with:您可以使用
set
用于Mongoose模式的方法:如果字符串等于',这将使字段删除。
用它来修剪字符串:
set:(a:string)=> a?.trim()===''?未定义:
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