我的问题是,我不知道如何检查对象的所有值是否为空,这样数据库就不会获得项目的所有详细信息为空。因此,我想将其中至少有一个值的对象保存到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);
}
});
请指导我如何实现这一点。
1条答案
按热度按时间pqwbnv8z1#
仅当定义了
supplier
时才添加$push
条件: