简体   繁体   中英

Removing document from multiple collections in MongoDB with MeteorJS

I have 5 collections - A, B, C, D, E. I have a document which is stored in A, and related to documents in the other 4 collections. I am using MeteorJS. Now, I have to delete the data in the document safely. In other words, the document has to be deleted in A, as well as its references in the others. Only after they are all removed, I have to show the user a success message. Right now, I have only:

A.remove(documentID);

I have to use a callback here to show the user the result. I am completely new to MongoDB and understand that cascade deletion of a row is not possible here as in SQL. I don't know how to write the code which will remove the document and its references (referenced by documentID in all) from all the collections and show the result to the user. Can somebody help please? Thanks a lot!

You're looking for collection hooks: https://github.com/matb33/meteor-collection-hooks

Collection hooks allow you to execute code before/after insert/updates/deletes on collections. Using your example, you could create a collection hook that looks something like:

A.after.remove(function(userId, doc) {
    B.remove({AReference: doc._id});
    C.remove({AReference: doc._id});
    D.remove({AReference: doc._id});
    E.remove({AReference: doc._id});
});

AReference will need to be whatever your related field is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM