Updating a child in Firebase Realtime Database doesn't do anything - firebase-realtime-database

When I try to update a child in Firebase Realtime Database it doesn't work. It seems as if the set doesn't do anything.
Future<void> changeCategory(Category c){
return remoteDataService.categoriesRefernece.child(c.id).set(c.toMap());
}
There's a list of categories in the database and the method above should update it. The toMap method converts the Cateory Object into Map<String, dynamic> and c.id stores the firebase-id of the Cateory

The problem was that the category in changeCategory didn't contain the new values so that there wasn't anything to update.

Related

Sembast best way to remove all documents

I'm using Sembast in a Flutter app. I have to refresh all the data in a store and need a way to removeall documents in a store. I looked at the API and only way I can see is either to get all keys and use them in a finder to delete them or drop the store and recreate it. Not sure if I overlooked something to support this?
This works for me -:
db.close();
await databaseFactoryIo.deleteDatabase(_database.path);
db = null;
The delete https://pub.dev/documentation/sembast/latest/sembast/StoreRef/delete.html method can (and should) be used. Maybe there should be a clear method that simply calls delete without filtering, it would be similar to the indexed db API...
Some info here: https://github.com/tekartik/sembast.dart/blob/master/sembast/doc/writes.md#delete-records
I did this:
var receiptStore = intMapStoreFactory.store("receipts");
final database = await databaseFactoryIo.openDatabase(dbPath, version: 2,
onVersionChanged: (Database db, int oldVersion, int newVersion) async {
if (oldVersion == 1) {
await receiptStore.delete(db);
}
});
so that I 'upgrade' the DB by deleting it.
You can use the sembast deleteAll method to delete all records in a Database, which returns the list of keys that have been deleted that you can use in whatever code you need to recreate the store.
If you do not need to recreate the store you can use the sembast clear method to delete all records in the store.

Append element to Firebase Array

How I could append an element to an array like that:
Using this code I'm overriding the old data:
let toUpdate = [book.id]
self.refUsers.child(localUser.key!).child("booksPurchased").setValue(toUpdate, withCompletionBlock: { (error, _) in
You could use this method: firebase.firestore.FieldValue.arrayUnion()
Example with angularfire2:
this.afs.collection('collection').doc(id).update( {
array: firebase.firestore.FieldValue.arrayUnion( 'newItem' )
});
For more information: https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue#arrayunion
In this case, you will have to read the existing data, then write it back with the new value added. Arrays like this are not always the best way to store lists of data if you want to perform a lot of append operations. For that, you're better off pushing data into a location using childByAutoId.
Reading and writing lists
Append to a list of data
Use the childByAutoId method to append data to a list in multiuser applications. The childByAutoId method generates a unique key every time a new child is added to the specified Firebase reference. By using these auto-generated keys for each new element in the list, several clients can add children to the same location at the same time without write conflicts. The unique key generated by childByAutoId is based on a timestamp, so list items are automatically ordered chronologically.
You can use the reference to the new data returned by the childByAutoId method to get the value of the child's auto-generated key or set data for the child. Calling getKey on a childByAutoId reference returns the auto-generated key.
You can use these auto-generated keys to simplify flattening your data structure. For more information, see the data fan-out example.
-https://firebase.google.com/docs/database/ios/lists-of-data
You could set the values of the keys in the array to true, and then set the value directly in an update.
So if 'newId' is the new item to add, maybe something like:
const update = {
[`/users/${localUser.key}/booksPurchased/${newId}`]: true]
}
firebase.db.ref().update(update);
Firebase docs example of an update:
https://firebase.google.com/docs/database/web/read-and-write

Spring Data Neo4j overwrites attributes

I tried writing a service, having an update(User) function using SDN 4.0.0.
The function should look, it there is a User in the database with the same id, and if so, overwrite this user with the new one.
Having a UserRepository which extends the GraphRepository<User> I wrote the following code:
User updateUser(User user){
if(userRepository.findOne(user.getId())!=null){
user = userRepository.save(user);
return user;
}else{
//Exception handling here
}
}
I now have the problem, that each user I update stays the way it was in the database because from the moment, the findOne(id) is called, all attributes of the user object get overwritten with the user as it is in the database.
I already fixed the problem, by adding an existsById(Long id) function in the repository annotated with the Query "Match (n:User) where ID(n)={0}".
However, I'm still interested, why SDN overwrites an object having the same id as an object i tried to get. I'm assuming there a references involved, but i can't really see the advantages of it.
This is by design, that when you load an entity from the database, it is the most recent version in the graph, thus overwriting any unsaved changes.
If you change the order of operations- load first, if it exists, then modify and save- you should be fine.

Split Database column value

I'm fetching data from database. I'm saving my data in string format like this
23,32
while fetching data from database my output is like
[{"transaction_id":"28,34"}]
but i want the out put in this format
[{"transaction_id":"28"},{"transaction_id":"34"}]
I'm not able to find the proper solution
You might want to mutate the data you're getting back with access mutator like:
public function getTransactionIdAttribute()
{
return //logic you want to apply to $this->transaction_id
}
But I suspect what you actually should do is set up your database relationship as many-to-many and make a join table that holds your transaction ids.

Update only the changed values on Entity object

how can i automatically update my entity objects changed values and save them to db.
I hava an Action like that
public ActionResult Update()
{
User userToUpdate = new User();
TryUpdateModel<User>(userToUpdate,ValueProvider);
BaseRepository.Context.AttachTo("User",userToUpdate);
BaseRepository.Context.SaveChanges();
return Json("");
}
ValuProvider : has the items that come
from the client as post data.
The problem on this code is the code update all the values but i want to update only the changed values.
How can i find the changed values on my entity object.
You should check out the ObjectContext.ApplyPropertyChanges Method
it is suppose to do what your asking for...
msdn
Two options:
On the View you could know the values that were changed by using Javascript and then you could pass that information to your controller.
You could simply compare the previous values (which you already have since you populated a view) and check each value before updating the DB.
I prefer last option, since at this point you could also check for data validation.
This is really a problem for your data access code, not anything to do with your controller. Pick an ORM that handles this for you and forget about the problem.

Resources