[英]Delete Document and all references in another Schema MongoDB
I have a schema for Forms
and another one for Documents
... 我有一个
Forms
的架构,另一个是Documents
的架构。
Each Document
must have a reference _id
of the Form
that is related to, so in database I can have many Documents
with the same Form._id
. 每个
Document
必须有一个参考_id
中的Form
是相关,所以在数据库中,我可以有很多Documents
具有相同Form._id
。
I want to know how to create a DELETE
function for the Forms
to do the following: 我想知道如何为
Forms
创建DELETE
函数以执行以下操作:
Documents
that have this Form._id
and DELETE
it all and then delete the Form
itself. Documents
具有此Form._id
并DELETE
所有,然后删除该Form
本身。 In our application we do it like that: When a user got deleted, delete also its corrosponding Scans & Categories 在我们的应用程序中,我们这样做:删除用户后,还删除其相应的扫描和类别
const scanModel = require("./Scan");
const categoryModel = require("./Category");
const userSchema = new mongoose.Schema({
...
})
userSchema.pre("remove", function(next) {
// 'this' is the user being removed. Provide callbacks here if you want
// to be notified of the calls' result.
scanModel.remove({ user: this._id }).exec();
categoryModel.remove({ user: this._id }).exec();
next();
});
Ok, so lets start of with some basic forms and documents in our database 好的,让我们从数据库中的一些基本表单和文档开始
db.forms.insertMany([
{ _id : 1, name : "Form 1"},
{ _id : 2, name : "Form 2"}
]);
db.documents.insertMany([
{ _id : 1, formId : 1, name : "Doc 1" },
{ _id : 2, formId : 1, name : "Doc 2" },
{ _id : 3, formId : 1, name : "Doc 3" },
{ _id : 4, formId : 2, name : "Doc 4" }
])
> db.forms.find()
{ "_id" : 1, "name" : "Form 1" }
{ "_id" : 2, "name" : "Form 2" }
> db.documents.find()
{ "_id" : 1, "formId" : 1, "name" : "Doc 1" }
{ "_id" : 2, "formId" : 1, "name" : "Doc 2" }
{ "_id" : 3, "formId" : 1, "name" : "Doc 3" }
{ "_id" : 4, "formId" : 2, "name" : "Doc 4" }
Then we can create a simple function to pass in the form id and find and delete all the documents for that form id. 然后,我们可以创建一个简单的函数来传递表单ID,并查找和删除该表单ID的所有文档。
function removeForm(formId){
var ids = db.documents.find({ formId : formId}, { _id : 1 } ).map(function(doc){ return doc["_id"]; });
db.documents.remove( { "_id" : { "$in" : ids } } );
db.forms.remove( { "_id" : formId } );
}
Then we can call removeForm. 然后,我们可以调用removeForm。
removeForm(1);
Then we'll see our documents and forms deleted 然后,我们将看到我们的文档和表格已删除
> db.forms.find()
{ "_id" : 2, "name" : "Form 2" }
> db.documents.find()
{ "_id" : 4, "formId" : 2, "name" : "Doc 4" }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.