我有這個集合Cart(cart schema)要洗掉,它被其他 2 個方案參考,Meal和Customer(所有者用戶,它的 schema 是:User Schema)。
如何通過將 HTTP 請求中的用戶 ID 作為 req.params.id 傳遞來洗掉購物車?
購物車架構
const mongoose = require('mongoose');
const idValidator = require('mongoose-id-validator');
const Schema = mongoose.Schema;
const cartItemSchema = new Schema ({
quantity: { type: Number, required: true },
itemId: { type: mongoose.Types.ObjectId, required: true, ref: 'Meal' }
});
const cartSchema = new Schema ({
cartItems : [
cartItemSchema
],
customer: { type: mongoose.Types.ObjectId, required: true, ref: 'User'}
});
cartSchema.plugin(idValidator);
module.exports = mongoose.model('Cart', cartSchema);
我創建了一個洗掉檔案的函式,但它不起作用,它回傳訊息:“已洗掉購物車。”,但不是真的,檔案仍保留在集合中。
const deleteCartByUserId = async (req, res, next) => {
const userId = req.params.uid;
let cart;
try {
cart = await Cart.find({ customer: userId });
} catch(err) {
const error = new HttpError('Something went wrong, could not delete cart.', 500);
return next(error);
}
if(!cart) {
const error = new HttpError('Could not find cart for this user id.', 404);
return next(error);
}
try {
Cart.deleteOne({ customer: userId });
} catch(err) {
console.log(err);
const error = new HttpError('Something went wrong, could not delete cart.', 500);
return next(error);
}
res.status(200).json({ message: 'Deleted cart.' });
};
uj5u.com熱心網友回復:
所以問題是你在洗掉一個函式呼叫之前錯過了等待。此外,我還更改了一些您的代碼以使其更清晰:
const functionHandler = fn =>
(req, res, next) =>
Promise
.resolve(fn(req, res, next))
.catch(next);
const deleteCartByUserId = functionHandler(async (req, res) => {
const { params: { uid: userId } } = req;
const cart = await Cart.findOneAndDelete({ customer: userId })
if(!cart) {
throw new HttpError('Could not find cart for this user id.', 404);
}
res.status(200).json({ message: 'Deleted cart.' });
});
在您的錯誤處理程式中間件中,您可以檢查錯誤型別,如果不是 HttpError 則使用內部服務器錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314292.html
