mongodb 防止将没有值的对象推送到mongoose模式

yyhrrdl8  于 2023-03-22  发布在  Go
关注(0)|答案(1)|浏览(139)

我的问题是,我不知道如何检查对象的所有值是否为空,这样数据库就不会获得项目的所有详细信息为空。因此,我想将其中至少有一个值的对象保存到mongoose。现在,当我编辑供应商品牌信息时,它总是将空的供应商数据推送到mongoose架构。

const editBrand = asyncHandler(async (requestObject, responseObject) => {
  const id = requestObject.params.id;
  const supplierInfo = {};
  const { name, madeIn } = await Brand.findById(id);
  if (
    name !== requestObject.body.name ||
    madeIn !== requestObject.body.madeIn
  ) {
    requestObject.body.slug = slugify(
      requestObject.body.name + " " + requestObject.body.madeIn
    );
  }
  if (requestObject.body.category) {
    const { id } = await Category.findOne({
      name: requestObject.body.category,
    });
    requestObject.body.category = id;
  }
  if (requestObject.body.supplier) {
    supplierInfo.name = requestObject.body.supplier.name
      ? format(requestObject.body.supplier.name)
      : undefined;
    supplierInfo.phone = requestObject.body.supplier.phone || undefined;
    supplierInfo.email = requestObject.body.supplier.email || undefined;
    supplierInfo.address = requestObject.body.supplier.address || undefined;
  }
  const update = await Brand.findByIdAndUpdate(
    id,
    {
      name: requestObject.body.name || undefined,
      madeIn: requestObject.body.madeIn || undefined,
      slug: requestObject.body.slug || undefined,
      category: requestObject.body.category || undefined,
      manufacturer: requestObject.body.manufacturer || undefined,
      $push: { supplier: supplierInfo || undefined },
    },
    { new: true, runValidators: true }
  );
  if (!update) {
    responseObject
      .status(417)
      .json({ message: "Unable to update record, please try again." });
  } else {
    responseObject.status(200).json(update);
  }
});

请指导我如何实现这一点。

pqwbnv8z

pqwbnv8z1#

仅当定义了supplier时才添加$push条件:

let updatedData = {
    name: requestObject.body.name || undefined,
    madeIn: requestObject.body.madeIn || undefined,
    slug: requestObject.body.slug || undefined,
    category: requestObject.body.category || undefined,
    manufacturer: requestObject.body.manufacturer || undefined,
  };
  if (requestObject.body.supplier) {
    supplierInfo.name = requestObject.body.supplier.name
      ? format(requestObject.body.supplier.name)
      : undefined;
    supplierInfo.phone = requestObject.body.supplier.phone || undefined;
    supplierInfo.email = requestObject.body.supplier.email || undefined;
    supplierInfo.address = requestObject.body.supplier.address || undefined;
    updatedData = {
      ...updatedData,
      $push: { supplier: supplierInfo },
    };
  }
  const update = await Brand.findByIdAndUpdate(id, updatedData, {
    new: true,
    runValidators: true,
  });

相关问题