products.map(async (prdct) => {
try {
let srchdPrdct = await ProductSchema.findById(prdct.product);
let dscntPrice =
Math.round(
srchdPrdct.price *
83.49 *
Math.round(100 - srchdPrdct.discountPercentage)
) / 100;
if (srchdPrdct) {
tempReceipt = await TempReceipt.findOneAndUpdate(
{
user: user._id,
products: {
$not: {
$elemMatch: { product: srchdPrdct._id },
},
},
},
{
$addToSet: {
products: {
product: srchdPrdct._id,
quantity: prdct.stock,
total_price: Math.round(dscntPrice * prdct.stock),
},
},
},
{ new: true, upsert: true }
);
} else {
throw new Error("Can't find provided Product");
}
} catch (error) {
ErrorHandler(res, req, error);
}
})
上面我已经给出了更新函数,我如何更新或插入它。
现在这是它的架构。
import mongoose from "mongoose";
const TempReceiptSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
products: [
{
product: {
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
},
quantity: { type: Number },
total_price: { type: Number },
},
],
address: {
type: mongoose.Schema.Types.ObjectId,
ref: "Address",
},
payMethod: {
payType: {
type: String,
},
details: {
type: mongoose.Schema.Types.Mixed,
},
},
status: {
type: String,
default: "",
},
});
const TempReceipt = mongoose.model("TempReceipt", TempReceiptSchema);
export default TempReceipt;
现在的问题是,我想创建一个临时收据,其中包含我所描述的所有信息,所以首先当我尝试从产品数组中逐一推送产品时,问题是如果我不这样做不使用该
srchdPrdct._id
搜索,然后它会添加所有产品,但如果我再次输入它,它会再次推送它们,所以我放置了一个条件检查器以确保数组中不应该有任何具有相同 id 的产品,以防止口是心非,但如果添加此检查,它会返回 null,即使我尝试从数据库中删除其中一个产品,它仍然显示 null。
但是我希望当我推送产品时它应该推送直到所有产品都没有推送为止,并检查是否已经存在具有相同 id 的产品。
该问题可能是由于
findOneAndUpdate
方法中的条件造成的。此条件检查产品是否尚未在 products
数组中。如果产品已经在数组中,则不会更新文档。
这是有问题的部分:
{
user: user._id,
products: {
$not: {
$elemMatch: { product: srchdPrdct._id },
},
},
}
此条件检查
products
数组中是否没有与 srchdPrdct._id
匹配的产品。如果没有这样的产品,它将更新文档。但是,如果有符合srchdPrdct._id
的产品,则不会更新文档。
这可能就是当您在更新文档后尝试查找文档时得到
null
的原因。如果由于不满足条件而导致文档未更新,findOneAndUpdate
将返回null
。
要解决此问题,您可以将
$addToSet
运算符与 $each
运算符结合使用,仅当数组中尚不存在多个项目时才将其添加到数组中。以下是修改代码的方法:
tempReceipt = await TempReceipt.findOneAndUpdate(
{ user: user._id },
{
$addToSet: {
products: {
$each: [
{
product: srchdPrdct._id,
quantity: prdct.stock,
total_price: Math.round(dscntPrice * prdct.stock),
},
],
},
},
},
{ new: true, upsert: true }
);
仅当数组中尚不存在时,才会将产品添加到
products
数组中。如果该产品已存在于数组中,则不会再次添加。