NeDB Update does not work - nedb

With NeDB the first statement will update the data correctly, but the second (using the doc value itself as key(and yes docs[i].ID is '2013000060')
won't work - even the result of the update function tells me that 1 row was changed.
1. oDB.update({ MYID: '2013000060' }, { $set: { "PAGE": 2 }}, ...
2. oDB.update({ MYID: docs[i].ID}, {$set: {"PAGE": 2}}, ...
Some ideas?

Take in account that updates in NeDB work asynchronously.
Anything you want to do after updating an object (and relying on that updated values) should be done inside the callback function you pass to the .update() call.

After fiddling around with NeDB datastore.js it turned out that this is sort of a weird timing problem.
The value is actually updated, but when a .find with a query was issued, the value was not yet persisted.
Anyway did I not go deeper to investigate the fact that using string literals yielded different results.

Could you copy paste the exact code you're using, the expected results and the actual results ? From the look of it it seems like you are using synchronous code where you should use callbacks.

Related

How to add multiple nested object keys in Dexie?

I'm in a loop where I add several new keys (about 1 to 3) to an indexeddb row.
The dexie table looks like:
{
event_id: <event_id>
<event data>
groups: {
<group_id> : { group_name: <name>, <group data> }
}
}
I add the keys using Dexie's modify() callback, in a loop:
newGroupNr++
db.event.where('event_id').equals(event_id).modify(x => x.groups[newGroupNr]=objData)
objData is a simple object containing some group attributes.
However, this way when I add two or three groups, only one group is actually written to the database. I've tried wrapping them in a transaction(), but no luck.
I have the feeling that the issue is that the modify()-calls overlap each other, as they run asynchronously. Not sure if this is true, nor how to deal with this scenario.
Dexie modify():
https://dexie.org/docs/Collection/Collection.modify()
Related:
Dexie : How to add to array in nested object
EDIT: I found the problem, and it's not related to Dexie. However, I do not fully understand why this fix works, perhaps something to do with that in javascript everything is passed by reference instead of value? My theory is that the integer newGroupNr value was passed as reference, and in the next iteration of the loop, before Dexie was able to finish, incremented, causing effectively two creations of the same key. This fixed it:
newGroupNr++
let newGroupNrLocal = newGroupNr
db.event.where('event_id').equals(event_id).modify(x => x.groups[newGroupNrLocal]=objData)
There's a bug in Safari that hits Dexie's modify method in dexie versions below 3. If that's the case, upgrade dexie to latest. If it's not that, try debugging and nailing down when the modify callbacks are actually happening. A transaction won't help as all IDB operations go through transactions anyway and the modification you do should by no means overwrite the other.

Doing an update instantly after read

Suppose I have multiple instances of an app reading a single row with a query like the following
r.db('main').
table('Proxy').
filter(r.row('Country').eq('es').and(r.row('Reserved').eq(false))).
min(r.row('LastRequestTimeMS'))
the 'Reserved' field is a bool
I want to guarantee that the same instance that have read that value do an update to set the 'Reserved' value to true to prevent other instances from reading it
can someone please point me to how I can make this guarantee?
Generally the way you want to do something like this is you want to issue a conditional update instead, and look at the returned changes to get the read. Something like document.update(function(row) { return r.branch(row('Reserved'), r.error('reserved'), {Reserved: true}); }, {returnChanges: true}).

request.object.previous() is not working in beforeSave()

I'm trying to check the current and previous value of an attribute in the beforeSave(). So i tried to use request.object.previous("attribute_name") but it is still returning the current changed value. Although the .ditry() is returning TRUE which means that the value is changed. Any idea what is wrong here ? I appreciate your feedback.
I think the .previous() isn't actually part of the Parse.com sdk, but simply inherited from backbone.
In a beforeSave handler, I have something like:
if(object.dirty("attr")) {
console.log("After: " + object.get("attr") + ", Before: " + object.previous("attr")); }
The value returned by 'previous' is always the same. Is this functionality actually
implemented? I've seen a few threads elsewhere that imply it's not -
if so, can you remove it from the API docs until it's done?
If it doesn't work, is the correct workaround to query the previous
object? Or does 'changedAttributes' work?
Oh, I now see that 'previous' is some cruft from Backbone.
source1
previous is a method inherited from Backbone.Model. It won't return the previous value of a field in Cloud Code.
source2
Might not be the answer you're looking for, so as a way to workaround the lack of the .previous implementation this this out:
Don't know if this is helpful or if it would be considered too costly
of a workaround, but you could add a column to the object that is
being updated that stores the previous value of the original column.
This would allow you to access the previous value in the AfterSave
function.

KnockoutJS proper way to update observableArray AJAX

In KnockoutJS, what's the proper way to update an observableArray of JSON data each time an AJAX command is run?
Right now, I'm blanking the array using something like viewmodel.items([]), then repopulating it with the JSON data from the server. Short of using the KnockoutJS mapping plugin (which might be the only way to do this) what is the correct path?
My server logic is going to send some of the same data each time, so I can't just iterate and push the items into the array unless I want duplicates.
//// Adding how I'm doing it today ////
I'm not sure why I'm doing it this way, but this is just how I initially figured out how to update. So basically, like I said before, I get JSON data, then I pass it to something like this:
_model.addIncident = function (json) {
var checked = json.UserTouches > 0 ? true : false;
_model.incidents.push({
id: ko.observable(json.IncidentIDString),
lastTouchId: ko.observable(json.UserLastTouchIDString),
weight: ko.observable(json.Weight),
title: ko.observable(json.Title),
checked: ko.observable(checked),
createdOn: ko.observable(json.IncidentCreatedOn),
servicename: ko.observable(json.Servicename),
inEdit: ko.observable(false),
incidentHistory: ko.observableArray(),
matchScore: ko.observable()
});
};
for each node in the JSON array. As you can see, I've got some custom observables in there that get build with every passing piece of data. Maybe this is the wrong way to go, but it's worked great up until now.
An observableArray is really just a normal observable with some extra methods for array operations.
So, if you want to set the value of an observableArray to a new array, you can just do:
viewModel.items(myNewArray)
The mapping plugin can help you update the existing items in an array with any updates. In this case, your UI will only be updated from any differences.
I know I'm way too late on this one as I found myself stuck in this situation just recently. We can use a simple Javascript util function as a work-around.
If you have already marked _model.incidents as observableArray, you can do something like this when binding the returned JSON data:
eval("_model.incidents("+JSON.stringify(json)+");");
It worked for me. Hope you have created your observable like this:
_model.incidents = ko.observableArray([]);

Deciding whether or not a run a function, which way is better?

I have some data being loaded from a server, but there's no guarantee that I'll have it all when the UI starts to display it to the user. Every frame there's a tick function. When new data is received a flag is set so I know that it's time to load it into my data structure. Which of the following ways is a more sane way to decide when to actually run the function?
AddNewStuffToList()
{
// Clear the list and reload it with new data
}
Foo_Tick()
{
if (updated)
AddNewStuffToList();
// Rest of tick function
}
Versus:
AddNewStuffToList()
{
if (updated)
{
// Clear the list and reload it with new data
}
}
Foo_Tick()
{
AddNewStuffToList();
// Rest of tick function
}
I've omitted a lot of the irrelevant details for the sake of the example.
IMHO first one. This version separates:
when to update data (Foo_Tick)
FROM
how to loading data (AddNewStuffToList()).
2nd option just mixing all things together.
You should probably not run the function until it is updated. That way, the function can be used for more purposes.
Let's say you have 2 calls that both are going to come and put in data to the list. With the first set up, checking the variable inside of the function, you could only check if one call has came in. Instead, if you check it in the function that calls the data, you can have as many input sources as you want, without having to change the beginning function.
Functions should be really precise on what they are doing, and should avoid needing information created by another function unless it is passed in.
In the first version the simple variable check "updated" will be checked each time and only if true would AddNewStuffToList be called.
With the second version you will call AddNewStuffToList followed by a check to "updated" every time.
In this particular instance, given that function calls are generally expensive compared to a variable check I personally prefer the first version.
However, there are situations when a check inside the function would be better.
e.g.
doSomething(Pointer *p){
p->doSomethingElse();
}
FooTick(){
Pointer *p = new Pointer();
// do stuff ...
// lets do something
if (p){
doSomething(p);
}
}
This is clumbsy because every time you call doSomething you should really check you're
not passing in a bad pointer. What if this is forgotten? we could get an access violation.
In this case, the following is better as you're only writing the check in one place and
there is no extra overhead added because we always want to ensure we're not passing in a bad pointer.
doSomething(Pointer *p){
if (p){
p->doSomethingElse();
}
}
So in general, it depends on the situation. There are no right and wrong answers, just pros and cons here.

Resources