tingodb
tingodb copied to clipboard
Bug when global variable is insert document?
Hello Sergey, I am playing around with your database, I have run into some unexpected behavior. Say, I want to insert 10 the same documents. Then this works:
for (var j = 0; j < 10; j++) {
var test = { hello:'world' };
collection.insert(test, { w: 1 }, function () {})
}
but this does not:
var test = { hello:'world' };
for (var j = 0; j < 10; j++) {
collection.insert(test, { w: 1 }, function () {})
}
What happens is that the first option indeed inserts 10 documents, while the last option only inserts 1. Behavior should essentially be the same though...
Hi @wgerven,
I believe that in both cases tingodb is correct. Essentially they are not the same. In the first case you try to insert a brand new object for every insert. In the second case you try to insert the same reference 10 times. And the behavior for each case is different.
To understand what tingodb does, add a console.log(test) inside callback function of every test, like this:
First case:
for (var j=0;j<10;j++){
var test = {hello:'world'};
collection.insert(test,{w:1},function(){
console.log(test);
});
}
Second case:
var test = {hello:'world'};
for (var j=0;j<10;j++){
collection.insert(test,{w:1},function(){
console.log(test);
});
}
The results of the first case:
$ node test
{ hello: 'world' }
{ hello: 'world' }
{ hello: 'world' }
{ hello: 'world' }
{ hello: 'world' }
{ hello: 'world' }
{ hello: 'world' }
{ hello: 'world' }
{ hello: 'world' }
{ hello: 'world', _id: 11 }
The results of the second case are:
$ node test
{ hello: 'world', _id: 2 }
{ hello: 'world', _id: 2 }
{ hello: 'world', _id: 2 }
{ hello: 'world', _id: 2 }
{ hello: 'world', _id: 2 }
{ hello: 'world', _id: 2 }
{ hello: 'world', _id: 2 }
{ hello: 'world', _id: 2 }
{ hello: 'world', _id: 2 }
{ hello: 'world', _id: 2 }
So that's why you have 10 inserts in the first test (10 different object references) and only one insert in the second (same object reference 10 times).
Hope i could help.
One other thing: you shouldn't use asynchronous calls inside loops (synchronous). Your program could have an unexpected behavior. You should use everything synchronous (using promises or synchronous calls from the API) or asynchronous (using loops from an async library)
Hello @diogoduailibe , thank you for your clarification. Indeed, the way you put it it does make sense. It pretty much comes down then on which point of view you assume with regards to the test object: From the DB or from application scope. As for your comment on using for; I agree with you. But at the time that I was posting my question, I was new to async programming so still transitioning into it being used to writing synchronous code :)