Ionic 2 Storage - Adding Records - ionic-framework

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.

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.

Related

Sembast read only 1 item

How can I read only 1 item from NoSql using Sembast? Every article about reading items are showing me creating a list but I only need just 1 item from databse.
You can access any record using the RecordRef api (and extension): https://pub.dev/documentation/sembast/latest/sembast/SembastRecordRefExtension.html
// Lint warnings will warn you if you try to use different types
var store = intMapStoreFactory.store();
// add a record, autogenerate a key
var key = await store.add(db, {'offline': true});
// Reading a single record falue
var value = await store.record(key).get(db);

How to use database data on Event OnBeforeCreate

I want to get the last data created on my database, more specifically the field called: "Saldo Atual" and after this get the form data field "Valor" and make a sum between this fields (the Old one "Saldo Atual" and the new "Valor") before create a new record and add this "Valor" and the sum of "Saldo Atual"+"Valor".
I don't know how to get the database last record
var saldoAtual =
record.saldoAtual = saldoAtual + record.valor;
And I want to know if the second line it's correct to save the sum of "Saldo Atual"+"Valor"
Based on my comment, I think that your records will need to have a Date_Created field. Then in your onBeforeCreate event the following script should work (this is untested, so you need to do your own testing):
var query = app.models.YourModelTheSameAsYourEventModel.newQuery();
query.sorting.Date_Created._descending();
query.limit = 1;
var lastrecord = query.run();
record.saldoAtual = lastrecord.saldoAtual + record.valor; //You may need to use lastrecord[0].saldoAtual
record.Created_Date = new Date();
Try that and do some testing to see if this yields your desired output.

Convert all collection in a single db into new dbs

can you please help me,
I am trying to copy all collections in a particular database into create new database and move that collection into it.But the following code does not work. and my colleciton name in the db contains two part ' mg2.data' ,'mg32.data' i want to create new database mg2 and copy collection name as data.
collection name mg2.data suppose to be in mg2 database and collection name data.
db.getCollectionNames().forEach(function( a ){
if(a!='system.indexes' ) {
var sp = a.split('.');
var dbName = sp[0];
var col = sp[1];
//print(dbName)
db[a].copyTo(db.getSiblingDB(dbName).getcCollection(col));
}
});
Here is my situation details.
I am having Db name Master and it contains about 60-70 collections its names like(mg1.data,mg2.data,mg3.data)
and i want it to be like
db name mg1 and collection name data
db name mg2 and collection name data and so on..
i am facing the problem that when in the first design write operation locks entire database(Master). i cannot go for sharding and all now.
I got this approach working for me.I dont know is this best aproach
db.getCollectionNames().forEach(function( a ){
if(a!='system.indexes' ) {
var sp = a.split('.');
var dbName = sp[0];
var col = sp[1];
print(dbName+'\n');
//db[a].copyTo(db.getSiblingDB(dbName).getcCollection(col));
db[a].find().forEach(function(d){ db.getSiblingDB(dbName)[col].insert(d); });
}
});

Creating optimal query of oracle db using EF

I have an Oracle database where I am storing information about customers.
One of the fields is user number.
My UserNumber column is type of text.
A user sends a number in various formats:
+44777XXXXXXX
777XXXXXXX
0777XXXXXXX
So far I have:
var list = context.UserDetails.Where(x => x.UserNumber == number).ToList();
I can also do this with:
var strippedNumber = ConvertNumberToBasic(number); // this will return me number as 777XXXXXXX
now
var list = context.UserDetails.Where(x => x.UserNumber.Contains(number)).ToList();
Is there a more optimal way for me to do this?
You really need to ask the customer what they need before you can write any code for this...

MongoDB C# offic. List<BsonObject> query issue and always olds values?

I have not clearly issue during query using two criterials like Id and Other. I use a Repository storing some data like id,iso,value. I have created an index("_id","Iso") to performs queries but queries are only returning my cursor if i use only one criterial like _id, but is returning nothing if a use two (_id, Iso) (commented code).
Are the index affecting the response or the query method are failing?
use :v1.6.5 and C# official.
Sample.
//Getting Data
public List<BsonObject> Get_object(string ID, string Iso)
{
using (var helper = BsonHelper.Create())
{
//helper.Db.Repository.EnsureIndex("_Id","Iso");
var query = Query.EQ("_Id", ID);
//if (!String.IsNullOrEmpty(Iso))
// query = Query.And(query, Query.EQ("Iso", Iso));
var cursor = helper.Db.Repository.FindAs<BsonObject>(query);
return cursor.ToList();
}
}
Data:
{
"_id": "2345019",
"Iso": "UK",
"Data": "Some data"
}
After that I have Updated my data using Update.Set() methods. I can see the changed data using MongoView. The new data are correct but the query is always returning the sames olds values. To see these values i use a page that can eventually cached, but if add a timestamp at end are not changing anything, page is always returning the same olds data. Your comments are welcome, thanks.
I do not recall offhand how the C# driver creates indexes, but the shell command for creating an index is like this:
db.things.ensureIndex({j:1});
Notice the '1' which is like saying 'true'.
In your code, you have:
helper.Db.Repository.EnsureIndex("_Id","Iso");
Perhaps it should be:
helper.Db.Repository.EnsureIndex("_Id", 1);
helper.Db.Repository.EnsureIndex("Iso", 1);
It could also be related to the fact that you are creating indexes on "_Id" and the actual id field is called "_id" ... MongoDB is case sensitive.
Have a quick look through the index documentation: http://www.mongodb.org/display/DOCS/Indexes