Search code examples
javascriptnode.jsmongodbmongodb-queryfeathersjs

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


I'm trying to remove document in two different collection using same id at same time. Is there any possibilities?

user collection:

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

worker collection:

{
    "_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
}

now i want to remove these two document at same time using userId.


Solution

  • Database adapters allow to call remove with null and a query that will remove all entries matching that query (see the documentation). In your case:

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

    Removing related entries (e.g. remove all workers for that user once the user has been removed) can be done in an 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 }
          });
        }
      }
    });