简体   繁体   中英

edit the last inserted record in mongodb

I am inserting two different objects into the db, i am doing this according to a certain criteria.

After that i am editing this record and setting the status to verified or not verified according to an amazon reply.

The problem is, i want to update the record that has been just inserted, since i am using findOneAndUpdate, only one record is being edited and it is not the last one it is the first.

Since the user can do as many purchases as he wants, he can have as many records as he want but only the first object found in the db having the userId sent as a param is edited.

what shall i use? the date and time when the object is inserted or what?

async createAndSendToAmazon(data) {
    try {
      const records = new this.model(data);
      const purchaseFromAppObjectRecord = await records.save();
      let userId = purchaseFromAppObjectRecord.UserData[0].userId;
      let receiptId = purchaseFromAppObjectRecord.receiptId;
      await sendToAmazon(userId, receiptId);
      await changeStatusToVerified(userId);
      return purchaseFromAppObjectRecord;
    } catch (error) {
      return error;
    }
  }
}
async function sendToAmazon(userId, receiptId) {
  const requestUrl = `https://appstore-sdk.amazon.com/version/1.0/verifyReceiptId/developer/2:smXBjZkWCxDMSBvQ8HBGsUS1PK3jvVc8tuTjLNfPHfYAga6WaDzXJPoWpfemXaHg:iEzHzPjJ-XwRdZ4b4e7Hxw==/user/${userId}/receiptId/${receiptId}`;
  console.log(requestUrl);

  fetch(requestUrl).then(function (response) {
    if (response.status === 200) {
      console.log(response.status);
      response.json().then(async function (data) {
        AmazonResolver.create(data);
      });
    } else {
      try {
        changeStatusToNotVerified(userId);
        console.log(response.status);
        response.json();
        console.log("err will not add amazon verification object");
      } catch (err) {
        console.log(err);
      }
    }
  });
}
async function changeStatusToVerified(userId) {
  try {
    await purchaseFromAppObjectModel.findOneAndUpdate(
      {
        UserData: { $elemMatch: { userId: userId } },
      },
      { $set: { status: "verified" } }
    );
  } catch (err) {
    console.log(err);
  }
}

I want to write down my question as a minimal one but i want you to see my functions.

// you can use sort aggregate function to sort users in desc order and update the last element first

async function changeStatusToVerified(userId) {
  try {
    await purchaseFromAppObjectModel.findOneAndUpdate(
      {
        UserData: { $elemMatch: { userId: userId } },
      },
      { $set: { status: "verified" } },
      { sort: { userId: -1 }, upsert: true, returnNewDocument: true }
    );
  } catch (err) {
    console.log(err);
  }
}
                  OR 


  async function changeStatusToVerified(userId) {
      try {
        await purchaseFromAppObjectModel.findOneAndUpdate(
          {
            UserData: { $elemMatch: { userId: userId } },
          },
          { $set: { status: "verified" } },
          { sort: { userId: -1 } }
        );
      } catch (err) {
        console.log(err);
      }
    }

if any one passes by here later on, this worked for me:

.findOneAndUpdate(
        {
          UserData: { $elemMatch: { userId: userId } },
        },
        { $set: { status: "verified" }, limit: 1 }
      )
      .sort({ $natural: -1 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM