Willem van Gerven Willem van Gerven - 2 months ago 9
Node.js Question

Trying out TingoDB: Issue passing global var to insert

I am testing and benchmarking a couple of embedded dbs using node.js. With TingoDB, anybody knows why this works

var test = {hello:'world'};
for (var j=0; j<size; j++) {
collection.insert(test, {w:1}, function(){})
}


but this not:

for (var j=0; j<size; j++) {
var test = {hello:'world'};
collection.insert(test, {w:1}, function(){})
}


That is, in the first case the database gets filled up with records till
size
, while in the second case only 1 entry is added.

Answer

There is no difference between both code examples provided by you.

Also, test is a global variable in both cases. for doesn't create it's scope, and due to hoisting your second code examples look like this:

var test;
for (var j = 0; j < size; j++) {
    test = { hello: 'world' };
    collection.insert(test, { w: 1 }, function () {});
}

As you can see, it's almost like the first one. The only difference is that it creates a new { hello: 'world' } object and assigns it to test variable each time. So collection.insert will get same data in both of your code examples.

I believe the problem is somewhere in the code you didn't provide here.