node.js - 如何删除从其他集合中引用的文档和子文档 - MongoDB Mongoose
问题描述
我有这个集合购物车(购物车模式)要删除,它被其他 2 个方案引用,膳食和客户(所有者用户,它的模式是:用户模式)。
如何通过将 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);
我创建了一个删除文档的函数,但它不起作用,它返回消息:'Deleted cart.',但不是真的,文档仍在集合中。
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.' });
};
解决方案
所以问题是您在删除一个函数调用之前错过了等待。此外,我还更改了一些代码以使其更清晰:
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 则使用内部服务器错误。
推荐阅读
- wix - Windows 安装程序:哪些文件被视为“版本化”
- android - 在手机上运行应用程序失败(Android Studio)
- java - 来自 Android 的“网络无法访问”,但在 Python 客户端上运行良好
- parsing - 在 LUA 中解析字符串
- java - 从 Java 调用存储过程
- java - 为什么 compareTo BigInteger while 循环不退出?
- html - 当我用关键帧制作另一个动画时,为什么不能为 scali 设置动画?
- sql - 结合使用 case 子句 SQL Server 2014 从别名列中删除 Char 10、Char 13 字符
- javascript - 缺少数字算法超时错误 (JavaScript)
- javascript - Bootstrap vue popover中带有v-show的动态内容