如果产品不存在,我愿意通过使用req.params.cart_id查找现有购物车并更新数组中的对象来更新现有购物车 推新产品
这是我的猫鼬模式
public class LargestNextGaussian
{
public static void main(String[] args)
{
// Random#nextDouble is implemented as
// (((long)next(26) << 27) + next(27)) / (double)(1L << 53)
// The "baseValue" here refers to the value that
// is obtained by combining the results of the
// two calls to "next"
long baseValueForV1 =
0b10000000000000000000000000000000000000000000000000001L;
double valueForV1 =
baseValueForV1 / (double)(1L << 53);
long baseValueForV2 =
0b10000000000000000000000000000000000000000000000000000L;
double valueForV2 =
baseValueForV2 / (double)(1L << 53);
// As of Random#nextGaussian:
double v1, v2, s;
do {
v1 = 2 * valueForV1 - 1;
v2 = 2 * valueForV2 - 1;
s = v1 * v1 + v2 * v2;
} while (s >= 1 || s == 0);
double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
double result = v1 * multiplier;
System.out.println("baseValueForV1 " + Long.toBinaryString(baseValueForV1));
System.out.println("baseValueForV2 " + Long.toBinaryString(baseValueForV2));
System.out.println("valueForV1 " + valueForV1);
System.out.println("valueForV2 " + valueForV2);
System.out.println("v1 " + v1);
System.out.println("v2 " + v2);
System.out.println("s " + s);
System.out.println("multiplier " + multiplier);
System.out.println("result " + result);
System.out.println();
}
}
让我说我有一个购物车:
baseValueForV1 10000000000000000000000000000000000000000000000000001
baseValueForV2 10000000000000000000000000000000000000000000000000000
valueForV1 0.5000000000000001
valueForV2 0.5
v1 2.220446049250313E-16
v2 0.0
s 4.930380657631324E-32
multiplier 5.4075951832589016E16
result 12.00727336061225
方法:
const shoppingCartSchema = mongoose.Schema({
user_id: { type: String, required: true},
cart_date: { type: String, required: true},
activeCart: { type: Boolean, required: true },
cart_content: [{
product_id: { type: String, required: true},
product_quantity: { type: Number, required: true},
}]
})
如果更新结果应为:
{
"_id" : ObjectId("5c6830c9a7e056443ce8befe"),
"user_id" : "5c4e1a3cbc446733801b5a54",
"cart_date" : "2019-02-16T15:48:25.464Z",
"activeCart" : true,
"cart_content" : [
{
"_id" : ObjectId("5c6830c9a7e056443ce8beff"),
"product_id" : "1",
"product_quantity" : 1
}
],
"__v" : 0
}
如果没有此类ID,则推送新产品:
router.post("/:update", (req, res, next) => {
const cart_id = req.params['update'];
const product_id = req.body.product_id;
Cart.update({"_id": cart_id},
//{Here to find the cart_content[index].product_id}
//{add +1 to product_quantity if product_id === to the req.product_id}
//{if no such product_id, push the new product {
"product_id": req.body.product_id,
"product_quantity": req.body.product_quantity
}).then(response => {
console.log(response);
}
});
答案 0 :(得分:0)
正如@mzparacha在我的问题评论中所述, 这是我的问题的答案: MongoDB Update array element (document with a key) if exists, else push
我认为您应该检查一下 stackoverflow.com/questions/41316056/…它正在描述解决方案 对于相同的问题,但不是很有效