I want to edit the field inside the collection of array of object

i have one query about the mongodb
there is one issue i want to change the field inside the collection of array of object i want to change it .
i want to change the paid to true if in the body req.body._id of is match to inside the object of paymentschedule _id.

{
    "customer": "62f75f6204a24bb48edae723",
    "product": "62cd46a3b325452b3efc6dd3",
    "downPayment": 140,
    "planOfInstallment": 12,
    "moneyRequiredToPay": 629,
    "contractInitiated": false,
    "contractStatus": "Normal",
    "moneyRecieved": 0,
    "investor": [
        {
            "investorDetail": "62f7542289326e783ae7feba",
            "money": 200,
            "date": "2022-08-13T09:38:33.476Z",
            "_id": "62f7711d932b45b68c7ae813"
        },
        {
            "investorDetail": "62f7542289326e783ae7feba",
            "money": 170,
            "date": "2022-08-13T09:38:33.476Z",
            "_id": "62f7711d932b45b68c7ae814"
        }
    ],
    "createdDate": "2022-08-13T09:38:33.476Z",
    "_id": "62f7711d932b45b68c7ae812",
    "paymentschedule": [
        {
            "monthName": "September",
            "dateToPay": "2022-09-25T21:00:00.000Z",
            "paid": false,
            "payment": 52.416666666666664,
            "paymentRecieveDate": null,
            "_id": "62f7711d932b45b68c7ae815"
        },
        {
            "monthName": "October",
            "dateToPay": "2022-10-25T21:00:00.000Z",
            "paid": false,
            "payment": 52.416666666666664,
            "paymentRecieveDate": null,
            "_id": "62f7711d932b45b68c7ae816"
        },
        {
            "monthName": "November",
            "dateToPay": "2022-11-25T21:00:00.000Z",
            "paid": false,
            "payment": 52.416666666666664,
            "paymentRecieveDate": null,
            "_id": "62f7711d932b45b68c7ae817"
        },
        {
            "monthName": "December",
            "dateToPay": "2022-12-25T21:00:00.000Z",
            "paid": false,
            "payment": 52.416666666666664,
            "paymentRecieveDate": null,
            "_id": "62f7711d932b45b68c7ae818"
        },
        {
            "monthName": "January",
            "dateToPay": "2023-01-25T21:00:00.000Z",
            "paid": false,
            "payment": 52.416666666666664,
            "paymentRecieveDate": null,
            "_id": "62f7711d932b45b68c7ae819"
        },
        {
            "monthName": "February",
            "dateToPay": "2023-02-25T21:00:00.000Z",
            "paid": false,
            "payment": 52.416666666666664,
            "paymentRecieveDate": null,
            "_id": "62f7711d932b45b68c7ae81a"
        },
        {
            "monthName": "March",
            "dateToPay": "2023-03-25T21:00:00.000Z",
            "paid": false,
            "payment": 52.416666666666664,
            "paymentRecieveDate": null,
            "_id": "62f7711d932b45b68c7ae81b"
        },
        {
            "monthName": "April",
            "dateToPay": "2023-04-25T21:00:00.000Z",
            "paid": false,
            "payment": 52.416666666666664,
            "paymentRecieveDate": null,
            "_id": "62f7711d932b45b68c7ae81c"
        },
        {
            "monthName": "May",
            "dateToPay": "2023-05-25T21:00:00.000Z",
            "paid": false,
            "payment": 52.416666666666664,
            "paymentRecieveDate": null,
            "_id": "62f7711d932b45b68c7ae81d"
        },
        {
            "monthName": "June",
            "dateToPay": "2023-06-25T21:00:00.000Z",
            "paid": false,
            "payment": 52.416666666666664,
            "paymentRecieveDate": null,
            "_id": "62f7711d932b45b68c7ae81e"
        },
        {
            "monthName": "July",
            "dateToPay": "2023-07-25T21:00:00.000Z",
            "paid": false,
            "payment": 52.416666666666664,
            "paymentRecieveDate": null,
            "_id": "62f7711d932b45b68c7ae81f"
        },
        {
            "monthName": "August",
            "dateToPay": "2023-08-25T21:00:00.000Z",
            "paid": false,
            "payment": 52.416666666666664,
            "paymentRecieveDate": null,
            "_id": "62f7711d932b45b68c7ae820"
        }
    ],
    "documentContract": [],
    "__v": 0,
    "id": "62f7711d932b45b68c7ae812"
}

Hi @arbabmuhammad_ramzan,

Have you checked out or considered using the filtered positional operator $[<identifier>]? It’s possible this may help you in updating the nested objects within the array fields of the sample document you provided.

If you require further assistance, please provide the following:

  1. Expected output based off the initial sample document you have already provided
  2. Specific values regarding the below statement:

if in the body req.body._id of is match to inside the object of paymentschedule _id.

  1. MongoDB version in use

Regards,
Jason

1 Like

Thanks a-lot for explaining I am stuck now in one place in the investors array of object its receivedMoney is not updates what api i have implemented let me share but its not working properly
The paymentSchedule is working but the investor field is not updating.

const payMonthlyInstallment = async (req, res) => {
  const contractDetails =  await Contract.findOneAndUpdate(
    
     { _id: ObjectId(req.params.id),"paymentschedule._id": ObjectId(req.body.month) },
      {
        $set: { "paymentschedule.$.paid": true,"paymentschedule.$.paymentRecieveDate": new Date()},
      },   
  ).populate("customer").populate({
    path : 'product',
    populate : {
      path : 'category'
    }
  });
  contractDetails.investor.map(async item => {
    let monthlyInstallment;
    switch(contractDetails?.product?.category?.profit){
      case 70: monthlyInstallment = ((((((contractDetails?.product?.price - contractDetails?.downPayment) * 25)/100) + (contractDetails?.product?.price - contractDetails?.downPayment)) / contractDetails?.planOfInstallment) ); break;
      case 30: monthlyInstallment = ((((((contractDetails?.product?.price - contractDetails?.downPayment) * 15)/100) + (contractDetails?.product?.price - contractDetails?.downPayment)) / contractDetails?.planOfInstallment) ); break;
      case 15: monthlyInstallment = ((((((contractDetails?.product?.price - contractDetails?.downPayment) * 5)/100) + (contractDetails?.product?.price - contractDetails?.downPayment)) / contractDetails?.planOfInstallment) ); break;
      default: monthlyInstallment = ((((((contractDetails?.product?.price - contractDetails?.downPayment) * 5)/100) + (contractDetails?.product?.price - contractDetails?.downPayment)) / contractDetails?.planOfInstallment) ) ; break;
    }
    
        const investorPercentage = ((item?.money/(contractDetails?.product?.price - contractDetails?.downPayment)) * 100)
    const amount = monthlyInstallment * investorPercentage / 100
    const updateContract =  await Contract.findOneAndUpdate(
    
      { _id: ObjectId(req.params.id),"investor._id": ObjectId(item?._id) },
       {
        $set: {
              "investor.$.moneyRecieved": {$add: [ "investor.$.moneyRecieved", amount ]},
           }
      }
   )
   console.log("contractDetails",updateContract)

  })
  res.send(contractDetails)
}

Hi @arbabmuhammad_ramzan,

For the code portion of your response, I’m not too familiar with Javascript so I will try any testing in mongosh .

The paymentSchedule is working but the investor field is not updating.

Can you advise which portion of the code you’re having issues with? My assumption is that it is this portion based off your comment but please confirm.

  const updateContract =  await Contract.findOneAndUpdate(
    
      { _id: ObjectId(req.params.id),"investor._id": ObjectId(item?._id) },
       {
        $set: {
              "investor.$.moneyRecieved": {$add: [ "investor.$.moneyRecieved", amount ]},
           }
      }
   )

Additionally, using the document you posted in the initial post, what are you expecting the output to be? If you could provide static values for the "_id", "investor._id", and amount in relations to the sample document you provided initially that would help greatly.

Lastly, please advise if you’re receiving any errors or unexpected behaviour regarding the investor field update. E.g. is the "moneyReceived" field within the "investor" array objects not being created or being created with the incorrect value or even in the incorrect object within the array etc.

One thing I also noted in the above code is that the "investor._id" in the query section of the findOneAndUpdate() refers to an ObjectId() value where as the sample document provided has the value in these fields as string. Is this expected? i.e.:

{
...
"investor": [
        {
            "investorDetail": "62f7542289326e783ae7feba",
            "money": 200,
            "date": "2022-08-13T09:38:33.476Z",
            "_id": "62f7711d932b45b68c7ae813" /// <--- String
        },
        {
            "investorDetail": "62f7542289326e783ae7feba",
            "money": 170,
            "date": "2022-08-13T09:38:33.476Z",
            "_id": "62f7711d932b45b68c7ae814" /// <--- String
        }
    ],
...
}

Regards,
Jason

2 Likes