0

As the title above, I am looking for a way to update mongoDB data(array, which has 21 fields in it) with overwriting using REST API Patch

below is my MongoDB Collection schema ('-' mark means a lower level of the top-level component)

Key Type
_id ObjectId
... ...
transactionLogs_docs Array
    - [0] Object
        - transactionID String
        - transactionType String
        - userId String
        - firstName String
        - lastName String
        - ... ...

currently with my code(coded with nodejs, express, vuejs, vuetify) when I update some data in the collection using REST API Patch, the data keys are gone except the one that I listed in the code.

What I wanna do is, partially update and replace values in the collection's transactionLogs_docs[0].fields and other fields out of transactionLogs_docs. (what I didn't mention in code, just maintain the original data)

below is my server-side patch function code.

// Modify Post
router.patch('/:id', async(req, res) => {
    const posts = await loadPostsCollection();
    await posts.updateOne(
        { "_id" : new mongodb.ObjectID(req.params.id) },
        {$set: {
            "transactionLogs_docs": {
                "0": {
                    "transactionId": req.body.transactionId, 
                    "transactionType": req.body.transactionType,
                    "userId": req.body.userId,
                    "firstName": req.body.firstName, 
                    "lastName": req.body.lastName              
                }
            },        
            "createdAt": req.body.createdAt, 
            "deviceName": req.body.deviceName, 
            "passCheck": req.body.passCheck,
            "max_temp": req.body.max_temp
        }},     
        { upsert: true }
    );
    res.status(201).send();
});
HzK
  • 47
  • 5
  • set value like this `transactionLogs_docs.0.transactionId: req.body.transactionId` change do same for every fields in `transactionLogs_docs`, – turivishal Dec 29 '20 at 07:20
  • This is happening because you are using `$set` and the field values you are receiving in `req.body` is `undefined`. MongoDB will explicitly change those values to `null` – Rudraprasad Das Dec 29 '20 at 07:24
  • @turivishal you definitely saved my day. I appreciate your advice thanks :) – HzK Dec 29 '20 at 07:28
  • you can see also the article below. [mongodb-partially-update](https://stackoverflow.com/questions/10290621/how-do-i-partially-update-an-object-in-mongodb-so-the-new-object-will-overlay) – myeongkil kim Dec 29 '20 at 08:38

0 Answers0