Home > Back-end >  (Solved) How to Delete document and sub documents referenced from others collections - MongoDB Mongo
(Solved) How to Delete document and sub documents referenced from others collections - MongoDB Mongo

Time:10-14

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

How can I delete the cart by passing as req.params.id the user's id from the HTTP request?

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

CodePudding user response:

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.

  • Related