简体   繁体   English

(已解决)如何删除其他集合引用的文档和子文档 - MongoDB Mongoose

[英](Solved) How to Delete document and sub documents referenced from others collections - MongoDB Mongoose

I have this collection Cart ( cart schema ) to delete and it is referenced with 2 other schemes, Meal and Customer (owner user, its schema is: User Schema).我有这个集合Cart购物车架构)要删除,它被其他 2 个方案引用, MealCustomer (所有者用户,其架构是:用户架构)。

How can I delete the cart by passing as req.params.id the user's id from the HTTP request?如何通过将 HTTP 请求中的用户 ID 作为 req.params.id 传递来删除购物车?

Cart Schema购物车架构

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);

I created a function to delete the document, but it doesn't work, it returns the message: 'Deleted cart.', but isn't true, the document remains in collection.我创建了一个删除文档的函数,但它不起作用,它返回消息:“已删除购物车。”,但不是真的,文档仍保留在集合中。

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.' });
};

So the porblem was that you missed an await before delete one function call.所以问题是你在删除一个函数调用之前错过了等待。 Also I've changed some of youre code to make it cleaner:此外,我还更改了一些您的代码以使其更清晰:

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.' });
});

In your error handler middleware you can check for error type and if it's not HttpError use internal server error.在您的错误处理程序中间件中,您可以检查错误类型,如果不是 HttpError 则使用内部服务器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何删除Mongoose中所有collections的所有文件 - How to delete all documents of all collections in Mongoose MongoDB和Mongoose:猫鼬可以在创建参考文档之前映射参考文档吗? - MongoDB & Mongoose: Can mongoose map referenced documents before referenced document is created? 使用mongoose过滤mongoDB中两个集合中的文档 - Filter documents from two collections in mongoDB using mongoose 如何在 mongoose 中创建子文档? MongoDB,NodeJS - How to create sub document in mongoose? MongoDB, NodeJS 使用 Mongoose 从 MongoDB 文档中删除一个键 - Delete a key from a MongoDB document using Mongoose 如何从 MongoDB 的数组字段中删除特定的子文档? - How to delete a specific sub-document from an array field in MongoDB? 如何从 Cloud Firestore 删除集合及其所有子集合和文档 - How to delete a collection with all its sub-collections and documents from Cloud Firestore Mongoose要求提供未被其他文件引用的文件 - Mongoose ask for documents not referenced by another document 猫鼬如何填充参考文档 - Mongoose how to populate referenced documents 如何使用查找mongodb hapijs为集合中的每个文档从其他集合中获取文档数组 - how to fetch array of documents from other collections for each document in a collection using lookup mongodb hapijs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM