如何在 mongodb on feathers 应用程序中同时使用相同的 id 删除两个不同集合中的文档

How to remove document in two different collection using same id at same time in mongodb on feathers application

我正在尝试同时使用相同的 ID 删除两个不同集合中的文档。有没有可能?

用户合集:

{
    "_id" : ObjectId("5a310315f685dd5038fecaaa"),
    "userId" : 3,
    "accountId" : 1,
    "userType" : "DRIVER",
    "firstName" : "Karthi",
    "lastName" : "keyan",
    "email" : "karthikeyan.a1@gmail.com",
    "password" : "a$KFYc6riMnqTuzXhR0ssKZQmejAU4RF8FthAIQD4sgOUcALesp7DaJxK",
    "phone" : "xyz",
    "updatedAt" : ISODate("2017-12-13T10:38:13.492Z"),
    "createdAt" : ISODate("2017-12-13T10:38:13.492Z"),
    "__v" : 0
}

工人合集:

{
    "_id" : ObjectId("5a310315f685dd5038fecaab"),
    "workerId" : 1,
    "accountId" : 1,
    "name" : "Karthikeyan",
    "email" : "karthikeyan.a1@gmail.com",
    "mobile" : "xyz",
    "type" : "DRIVER",
    "joinDate" : ISODate("2017-12-13T10:38:13.070Z"),
    "assignedVehicleId" : "23423231",
    "licenseNumber" : "TN2506",
    "createdBy" : "1",
    "createdDate" : ISODate("2017-12-13T10:38:13.070Z"),
    "updatedBy" : "1",
    "updatedDate" : ISODate("2017-12-13T10:38:13.070Z"),
    "regularHours" : 3600,
    "regularRates" : 1500,
    "overtimeRates" : 400,
    "distanceRate" : 1000,
    "stopRate" : 50,
    "workerStatus" : "AVAILABLE",
    "userId" : 3,
    "__v" : 0
}

现在我想使用 userId 同时删除这两个文档。

数据库适配器允许使用 null 调用 remove 和一个将删除所有匹配该查询的条目的查询(请参阅 the documentation)。你的情况:

app.service('users').remove(null, { query: { userId: 3 } });
app.service('workers').remove(null, { query: { userId: 3 } });

删除相关条目(例如,删除用户后删除该用户的所有工作人员)可以在 after hook:

中完成
app.service('users').hooks({
  after: {
    async remove(context) {
      const user = context.result;

      await context.app.service('workers').remove(null, {
        query: { userId: user.userId }
      });
    }
  }
});