Muhammad
Muhammad

Reputation: 349

Ionic 2 Storage - Adding Records

I am new to the NoSQL world and since Ionic 2 by default supports simple key-value DB, I was to some help here.

My app has a very large form. How do I go about saving new records? How do I retrieve those particular records?

Currently, to save a new record, I am doing something like this:

save(data){
    let newData = JSON.stringify(data);
    this.storage.set('reports', newData);
}

The problem with this is it overwrites the record instead of inserting a new record.

I am retrieving records like this:

getData() {
    return this.storage.get('reports');  
}

How do I go about fetching a particular record using certain values in the stored JSON?

Thanks.

Upvotes: 0

Views: 1135

Answers (1)

Bala Abhinav
Bala Abhinav

Reputation: 1348

What you would have to do is make reports as an array and set it to the storage. everytime you need to insert a new record, do a

function(newData){
    var some_variable = storage.get('reports'); //get Existing Table
    some_variable.push(newData); //Inserts the new record to array
    storage.set('reports', some_variable); //Saves report with updated data
}

For getting a particular report alone, I hope you have some id or a unique attribute y which you can distinguish a report. Assuming you have the report json as below :

var report {id : "UniqueID", name : "A sample report json"}

Then to get the report,

function(reportId){
    var reports = this.storage.get('reports');//fetches your reports Array
    var wantedReport = {};//Variable to store the wanted report
    reports.forEach(function(r){ //Looping the array.You can use a forloop as well
        if(r.id === reportId){ //filtering for the wanted reportId
            wantedReport = r; // storing the report to variable
        }
    })
    return wantedReport; //Returning the report to the caller.
}

Alternatively, If you are used to Sql and want a Sql-like way of storing these data then you can install the Sqlite cordova plugin and store your data in a Sqlite DB.

Upvotes: 4

Related Questions