javascript 不要在mongodb文档中存储带有空字符串值的键

xzv2uavs  于 2023-01-19  发布在  Java
关注(0)|答案(3)|浏览(95)

我想在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'
}

非常感谢你的帮助!

cngwdvgl

cngwdvgl1#

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)
7dl7o3gd

7dl7o3gd2#

您可以将set方法用于Mongoose模式:

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

如果字符串等于“”,则将取消设置字段。
使用此选项修剪字符串:set: (a: string) => a?.trim() === '' ? undefined : a

disbfnqx

disbfnqx3#

您可以通过使用以下内容过滤req.body空属性来构建对象:

const post = {};
for (const key in req.body) {
    const value = req.body[key];
    if (value && value !== '') {
        post[key] = value
    }
}
await Post.create(post);

相关问题