Is this a solid practise?

I have a large document (~20KB) and through an AWS lambda i modify it. Almost all fields are updated during that process and through an http Request i want to replace the document with the new object that the lambda sends.

The process below achieves that, i was just wondering whether there’s another (better) way to do that since it feels weird to delete the _id field from my object (otherwise i get the error of trying to modify the _id field which is immutable) in order to replace it.

I will appreciate any advice. Thanks in advance!

    const reqBody = body.text();
    const jsonRequest = JSON.parse(reqBody);
    var myObj = jsonRequest.myObj;
    
    myObj.updatedAt = new Date().getTime();
    let id = myObj._id;
    delete myObj._id;
    
    const options = { "upsert": false };

    response.myObj= await context.services.get("myInstance")
    .db("myDB")
    .collection("myCollection")
    .replaceOne({"_id": BSON.ObjectId(id) }, myObj, options);
   

Hi @Panagiotis_Milios welcome to the community!

I think you can get away with:

    const reqBody = body.text();
    const jsonRequest = JSON.parse(reqBody);
    var myObj = jsonRequest.myObj;
    
    myObj.updatedAt = new Date().getTime();

    const options = { "upsert": false };

    response.myObj= await context.services.get("myInstance")
    .db("myDB")
    .collection("myCollection")
    .replaceOne({"_id": myObj._id }, myObj, options);

Please note that this is untested code.

replaceOne should not complain about modifying _id since I don’t think you’re changing it. If this doesn’t work for you, please post the original document, the document you’re trying to replace it with, and the error message you’re seeing.

Best regards
Kevin

1 Like

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.