var docs = [];
server.on('add', function(item){
docs.push(item);
});
setInterval(function(){
save(docs);
}, 3000);
var save = function(array) {
var items = array.slice(0); // copy array
array.length = 0; // clear array
mongodb.insert(items, function(){
// ...
});
};
I would like to save documents to RAM and next save to mongodb. Is this code safe?
Mongodb server is in EU, application server is in US. It is added 2-3k items per sec to the base. I would like to decrease quantity of connections. My question: It is possible that during save to the base the variable will be modificate (in 'add')
This depends on weather mongodb.insert(docs); performs the operation for all elements in one go. If it triggers a callback after each inserted element, then your code is not safe (because your array will be cleared after the first inserted element).
If however the operation is synchronous for all elements then your code should be safe.