Removing document from multiple collections in MongoDB with MeteorJS

我们两清 提交于 2019-12-12 05:20:01

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/35848207/removing-document-from-multiple-collections-in-mongodb-with-meteorjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!