Search code examples
javascriptangularjscloudantfitbit

How to update database entries instead of creating new entries


I'm currently working on a web app where we use wearables to monitor some vital parameters. For integration test purposes i'm using a fitbit. The app is written in angular/javascript, the database is from cloudant. My question is: How do you keep the database entries updated in general? I want to request the data from the wearable every two hours and update the already existing entry for that day instead of creating a new one to prevent duplicates.

So far i have thought of two things:

  1. store today's data in a variable, especially the ID of the database entry to update every few hours and clear the variable at 0:00.
  2. before every update get all entries and check if there is an entry for today's date. If so get the ID of said entry and update it, otherwise create a new one

I'm not really satisfied with either of the solutions.

Thanks in advance


Solution

  • Updating existing documents in Cloudant/CouchDB can be done, but you open yourself up to conflicts. Creating a new document for each sample is actually a good approach for many "IoT" type scenarios using Cloudant. You can then use a view to materialise the data. Your documents could look like this:

    {
       "timestamp": "2016-12-01T13:25:02.000Z",
       "type": "pressure",
       "value": 110.0
    }
    

    Then use a design document that emits the data, along the lines of

    function(doc) {
        if (doc && doc.timestamp && doc.value && doc.type) {
            var ts = Date.parse(doc.timestamp);
            emit([doc.type, ts], doc.value);
        }
    }
    

    More info here: https://cloudant.com/blog/introduction-to-document-conflicts-part-three/