I want to import some data from a json file (which contains a json array of objects) into mongodb using mongoose. When the route '/import' is called I load the file via "require" and start iterating.
router.get('/import', function (req, res) {
var data = require('../import/1.json');
nTotal = data.length;
for (var i = 0; i < nAppCount; i++) {
var obj = new MyObject(data[i]);
obj.save(check);
}
});
Since JSHint warns me not to "make functions inside a loop", I created my function called check as follows:
function check (err,doc){
nProcessed++;
if (err) {
logger.log('error', err.message, err.errors);
} else {
logger.log('debug', "%d of %d processed",nProcessed, nTotal);
if (nProcessed===nTotal) {
res.render('index');
}
}
}
Everything works as expected until the end but when all objects are processed I get:
ReferenceError: res is not defined
Isn't "check" supposed to "know" res variable being a closure function? How am I going to access "res"?
Note: I can make it work if I ignore jsHint warning.