Javascript 如何从Mongoose中的购物车创建订单并删除购物车
我正在努力: a) 从我的当前购物车创建订单 b) 使用“选择”中的选定对象属性填充订单响应 c) 最后,我想删除购物车 我尝试了以下方法,但以下是我的问题:Javascript 如何从Mongoose中的购物车创建订单并删除购物车,javascript,mongodb,express,mongoose,mongoose-schema,Javascript,Mongodb,Express,Mongoose,Mongoose Schema,我正在努力: a) 从我的当前购物车创建订单 b) 使用“选择”中的选定对象属性填充订单响应 c) 最后,我想删除购物车 我尝试了以下方法,但以下是我的问题: 即使确实填充了prevProductsQuantity常量,结果响应也不会返回填充 我创建了cartClear函数来接收购物车id并从模型中删除文档,但它不起作用 我能够创建许多“相同”的订单,因此我认为我需要使用条件a进行管理,但不确定在哪里 我期待的回应是: { "success": true, "dat
prevProductsQuantity
常量,结果响应也不会返回填充{
"success": true,
"data": {
"_id": "607ed5c425ae063f7469a807",
"userId": "6071aed0ed7ec9344cf9616c",
"productsQuantity": [
{
"_id": "607f2507994d5e4bf4d91879",
"productId": {
"productRef": "463b8bb7-6cf6-4a97-a665-ab5730b69ba2",
"productName": "table",
"brand": "boehm llc",
"price": 713,
"__v": 0,
"createdAt": "2021-04-09T18:31:43.430Z",
"updatedAt": "2021-04-09T18:31:43.430Z"
},
"quantity": 2,
"updatedAt": "2021-04-21T15:12:51.894Z",
"createdAt": "2021-04-21T15:12:51.894Z"
}
],
"__v": 0
}
++删除购物车++
我目前得到的答复是:
{
"success": true,
"data": {
"state": "pending-payment",
"_id": "6080507a0c758608d0dc585c",
"userId": "6071aed0ed7ec9344cf9616c",
"totalPrice": 1426,
"productsQuantity": [
{
"_id": "607f2507994d5e4bf4d91879",
"productId": "60709d8f24a9615d9cff2b69",
"quantity": 2,
"updatedAt": "2021-04-21T15:12:51.894Z",
"createdAt": "2021-04-21T15:12:51.894Z"
}
],
"createdAt": "2021-04-21T16:19:06.056Z",
"updatedAt": "2021-04-21T16:19:06.056Z",
"__v": 0
}
**而且购物车没有删除**
这是我为这些目的键入的代码
非常感谢您的指导
router.post('/',[isAuthenticated],异步(req,res,next)=>{
试一试{
const cart=wait CartModel.findOne({userId:req.user})。填充({
路径:“productsQuantity.productId”,
选择:{
价格:1,,
品牌:1,
产品名称:1,
产品编号:1,
图片:1
}
});
const prevProductsQuantity=购物车
.get('productsQuantity')
.map((el)=>el.toObject());
const totalPriceByProduct=prevProductsQuantity.map(
(产品)=>product.productId.price*product.quantity
);
const totalPrice=totalPriceByProduct.reduce(函数(a,b){
返回a+b;
});
const result=await OrderModel.create({
userId:req.user,
totalPrice:totalPrice,
声明:“待付款”,
productsQuantity:prevProductsQuantity
});
常量cartClear=(id)=>
CartModel.deleteOne({
_id:id.\U id
});
res.status(200).json({
成功:没错,
数据:结果
});
cartClear(`${cart.\u id.toString()}`);
}捕获(错误){
下一步(错误);
}
});代码>您没有解析deleteOne承诺,缺少异步和等待
const cartClear = async (id) =>
CartModel.deleteOne({
_id: id
});
await cartClear(`${cart._id.toString()}`)
res.status(200).json({
success: true,
data: result
});
你是对的我没有正确地履行诺言。。我使用了它,它起了作用:CartModel.findbyidandelete(cartId,function(err){if(err)console.log(err);console.log('Successful deletation');});//谢谢你的提示