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);
}
})
Above I have given the updating function that how I am updating or inserting it.
Now here is its schema.
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;
Now the issue is that I want to create a temporary receipt where I have all of the info that I have described so first when I try to push products one my one-by-one from a product array the issue is that if I don’t use that srchdPrdct._id
search then it adds the all products but again if I enter it then again it pushes them so I put an condition checker to ensure that there shouldn’t be any product in arrays which have same id like to prevent duplicity but if add this check it returns null even if I try to delete one of the product from database it still says null.
But I want that when I push products it should push until all the products wasn’t pushed and also check whether is there any product already exists with same id or not.