Mongo DB query for updaitng the document in a collection difficult problem

Viewed 53

i have three collection one is User, Store, Map

Map: Collection :
{
"_id" : ObjectId("5fc91244c99e953e48b3f1fc"),
"serviceProviderAdminId" : "5fc91242c99e953e48b3f1fa",
"storeId" : "5f59cbceefca3f304c81e042",
"createdAt" : ISODate("2020-12-03T16:28:52.164Z"),
"role" : "spadmin",
"__v" : 0
}

User Collection:

{
"_id" : ObjectId("5fc91242c99e953e48b3f1fa"),
"mNumber" : 98917,
"area" : "Noida",
"email" : "bhuraspadmin@gmail.com",
"name" : "bhurasuar sp admin",
"role" : "spadmin",
"__v" : 0
}

Store Collection:

{
"_id" : ObjectId("5f59cbceefca3f304c81e042"),
"title" : "bhura suar",
"storeCommunicationEmailId" : ""
}

I want to update storeCommunicationEmailId field of document in collection Store. where Updating criteria is that I have to find user from User collection where the _id of User and serviceProviderAdminId of Map collection is same and get the email value of matching result from user collection and update the email into the document of Store collection where the _id in a document of Store Collection and storeId of the document of Map collection is same.

basically the result of query should be Store collection

{
"_id" : ObjectId("5f59cbceefca3f304c81e042"),
"title" : "bhura suar",
"storeCommunicationEmailId" : "bhuraspadmin@gmail.com"
}

I'm new to mongo db please help and thanks in advance..!!

1 Answers

Define a function with the serviceProviderAdminId and storeId as arguments. Then find the relevant user from the UserModel. Finally update the store collection.

const testFunction = async(serviceProviderAdminId, storeId) => {
  // Find the user with the matching serviceProviderAdminId
  const user = await UserModel.findOne({
    _id: serviceProviderAdminId
  });

  // Update the store with the user's email
  await StoreModel.updateOne({
    _id: storeId
  }, {
    storeCommunicationEmailId: user.email
  }, {
    new: true
  });
}

Related