este es el botón de eliminación de mi producto para eliminar el producto del carrito, estoy acostumbrado aquí ajax:
carro.hbs
<button href="/remove-product" id="{{this.product._id}}" class="btn btn-danger" onclick="removeProduct ,('{{this.product._id}}'), confirm('Are you sure you want to remove the product {{this.product.Name}} ?')" > remove </button> function removeProduct(cartId, proId) { $.ajax({ url: '/remove-product', data: { product: proId, cart: cartId, }, method: 'post', success: (response) => { if (response.removeProduct) { alert('Product Removed Successfully'); location.reload(); } else { document.getElementById(proId).innerHTML = response.removeProduct; } }, }); }user.js este es mi archivo js
router.post('/remove-product', (req, res) => { userHelpers.removeProduct(req.body).then((response) => { res.json(response); }); });para retirar el producto, este es el cable para retirar el producto del carrito aquí, pasé proId y cartId user-helpers.js
removeProduct: (details) => { return new Promise((resolve, reject) => { db.get() .collection(collection.CART_COLLECTION) .updateOne( { _id: objectId(details.cart) }, { $pull: { products: { item: objectId(details.product) } }, } ) .then((response) => { resolve({ removeProduct: true }); }); }); };Cuando usamos Ajax, debemos ser muy conscientes de cómo se envían los datos. Quiero decir aquí estamos enviando los datos
data: { product: proId, cart: cartId, },estos son los datos y el método de envío es posterior , por lo tanto, en el archivo js también es necesario usar el método posterior , he resuelto este problema yo mismo aquí está el código,
aquí está el botón, cart.hbs
<button id=" Remove" class=" btn btn-danger" onclick=" removeProduct ('{{this._id}}','{{this.product._id}}')"> remove</button> <script> function removeProduct(cartId, proId) { $.ajax({ url: '/remove-product', data: { product: proId, cart: cartId, }, method: 'post', success: (response) => { if (response.removeProduct) { alert("Product Removed Successfully") location.reload() } else { document.getElementById(proId).innerHTML = response.removeProduct } } }); }; </script>usuario.js
router.post('/remove-product',(req,res)=>{ userHelpers.removeProduct(req.body).then(async(response)=>{ res.json(response) }) })y este es el codigo para retirar el producto del carrito
ayudantes-de-usuario.js
removeProduct:(details)=>{ return new Promise ((resolve,reject)=>{ db.get().collection(collection.CART_COLLECTION) .updateOne({_id:objectId(details.cart)}, { $pull:{products:{item:objectId(details .product)}} } ).then((response)=>{ resolve({removeProduct:true}) }) }) }