Hi I am trying to upload multiple files, file writing is proper. but I want to move the files into mongo grid fs, the 1st file is only moving properly rest of the file are not moving into grid fs and not unlinking also.
Here is my code:
for (var i = 0; i < files.length; i++) {
(function(i) {
var singleFile = files[i];
var fileData = JSON.parse(files[i].name);
var fileName = fileData.fileName;
var fileType = files[i].type;
var uniqId = fileData.attachmentId;
var targetPath = "./attachments/" + uniqId;
var tmp_path = files[i].path;
console.log("uniqId : " + uniqId);
//uploadFile(tmp_path,targetPath,fileName,uniqId,fileType);
fs.readFile(tmp_path, function(err, data) {
fs.writeFile(targetPath, data, function(err) {
if (!err) {
mongoose.connect(configSettings.mongodb.ip, configSettings.mongodb.databasename, configSettings.mongodb.port, function(err, succ) {
var id = new ObjectID(uniqId);
new GridStore(mongoose.connection.db, id, fileName, 'w', {
'content_type': 'application/octet-stream'
}).open(function(err, gs) {
gs.writeFile(targetPath, function(err) {
if (err) {
console.log("err");
}
gs.close(function(err) {
console.log("success");
fs.unlink("./attachments/" + uniqId, function(err) {
console.log("err : " + err);
console.log(uniqId + ' ::successfully deleted ');
});
mongoose.connection.close();
});
});
});
});
}
});
});
})(i);
}
res.send("success");
This one i have tried with closure function, even i have tried with creating separate function also but the same result comes(only one file inserted and unlinked).
what i have to do in this case to store all files in gridfs and unlink from the temporary folder?