'Cascade Delete in mongo

I am new to MongoDB. I created 4 collections & they are connected with each other. (I am using node.js to write it)

Here, it's my question. How can I delete all records at once? Is there something like deep level population?

This one holds all models.

const DataModel = mongoose.Schema({
    _id: { type: mongoose.Schema.Types.ObjectId, ref: 'User', require: true},
    order: { type: mongoose.Schema.Types.ObjectId, ref: 'Order', require: true},
});

User model

const userSchema = mongoose.Schema({//other stuff});

Order model

const orderSchema = mongoose.Schema({
    product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true },
    //other stuff
});

Product model

const productSchema =  mongoose.Schema({//other stuff});

I can delete the entry with these code from the database, but the other entries still there

exports.delete_data = (req, res, next) => {
const id = req.params.userId;
userDataModel.deleteOne({_id: id})
    .exec()
    .then(docs => {
        res.status(200).json({
            message: 'Record Deleted',
            request: {
                type: 'POST'
            }
        });
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });
};

Update: However, I wonder, Could I call other defined delete functions for order, product inside delete_data



Solution 1:[1]

As @Geert-Jan suggest, cascade delete is my solution. The link that geert-jan gave solve my problem. However, I wonder, Could I call other defined delete functions for order, product inside delete_data

Solution 2:[2]

i did this and it could be good for someone who wants to delete documents in cascade linked to any field of a model.

async blackHole() {
        try {
            const rtn = new ApiResponse<any>();
            const userId = id;
            const accountId = mongoose.Types.ObjectId(id);
            var CollectionNames: any[] = [];
            mongoose.connection.db.listCollections().toArray(function (err, collections) {
                CollectionNames = collections.map(c => c.name);
                CollectionNames.forEach((element: any) => {
                    mongoose.connection.db.collection(element).deleteMany({ "account": accountId });
                });
            });
            const accountController = new AccountController(this.wsParams);
            await accountController.delete(id)
            await super.delete(userId);

            return rtn;
        } catch (error: any) {
            const rtn = new ApiResponse<any>();
            rtn.message = error;
            rtn.success = false;
            rtn.status = 422;
            return rtn;
        }
    }

I hope you can use it :D

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kaan Taha Köken
Solution 2 OC.