See my code below.
exports.myexports = (req, res) => {
var arrayname = new Array();
Hello.find({},function(error,fetchAllHellos)
{
if(fetchAllHellos)
{
async.eachSeries(fetchAllHellos, function(Hello, callback)
{
var hArr = {};
var image = {};
hArr['_id'] = Hello._id;
hArr['myname'] = Hello.name;
/* Use asyn Parallel method for waiting those functions value */
async.parallel
(
[
function(callback)
{
fetchingDetails(Hello._id, function(err, fetchAllDetails)
{
bArr['address'] = fetchAllDetails;
async.eachSeries(fetchAllDetails, function(fetchAllDetails, callback)
{
async.parallel
(
[
function(callback)
{
fetchingMyImage(fetchAllDetails._id, function(err, wer)
{
image[fetchAllDetails._id] = wer;
callback(err); //Forgot to add
})
}
],
function(err)
{
//console.log(image);
arrayname.push(image);
//bArr['image'] = image
callback(err);
}
);
});
callback(err); //Forgot to add
});
}
],
function(err)
{
arrayname.push(hArr);
callback(err);
}
)
},
function(err)
{
console.log(arrayname); //This should give you desired result
});
}
else
{
return res.json({"status":'error'})
}
});
};
function fetchingMyImage(mid, callback)
{
UserImage.find({myid:mid},function(error,fetchallImages)
{
callback(error,fetchallImages);
});
}
I want like this array
user
[
id = 'lkjlk',
myname = 'helloname'
address = [
object,
]
image = [
myid = image.png
]
]
Made changes in your code. Let me know if it helps you.
Please go through the code and let me know, whether you understood the changes or not.
exports.myexports = (req, res) => {
var arrayname = new Array();
Hello.find({},function(error,fetchAllHellos)
{
if(fetchAllHellos)
{
async.eachSeries(fetchAllHellos, function(Hello, callback)
{
var hArr = {};
var image = [];
hArr['_id'] = Hello._id;
hArr['myname'] = Hello.name;
//Read doc before you can start using.
async.parallel
([
function(callback)
{
fetchingDetails(Hello._id, function(err, fetchAllDetails)
{
bArr['address'] = fetchAllDetails;
async.eachSeries(fetchAllDetails, function(eachDetail, callback)
{
fetchingMyImage(eachDetail._id, function(err, wer)
{
image.push({eachDetail._id : wer;
callback(err);
})
}, function(err)
{
console.log(image);
arrayname.push({images :image});
callback(err);
});
});
}
],
function(err)
{
arrayname.push(hArr);
callback(err);
})
},
function(err)
{
console.log(arrayname); //This should give you desired result
console.log(arrayname.images)// Array of images will be consoled here.
//callback(err);
});
}
else
{
return res.json({"status":'error'})
}
});
};
function fetchingMyImage(mid, callback)
{
UserImage.find({myid:mid},function(error,fetchallImages)
{
callback(error,fetchallImages);
});
}
Related
i want to iterate over an array, however my array is an observer. i have tried several ways, like converting to an array. nothing works.
does anyone have a suggested solution?
i'm pretty stuck on this.
here is my code:
var vm = new Vue({
el: '#app',
data() {
return {
segmenteConfig: []
}
},
methods: {
async loadData(type) {
var url = null;
console.log("used configs -> ", this.segmenteConfig);
this.segmenteConfig.forEach(segmenteConfig => {
if (segmenteConfig.type === type) {
url = segmenteConfig.url;
console.log("used configs url -> ", url);
}
})
}
loadConfig() {
var config = [];
axios.get("ressources/segmente.json")
.then(response => {
response.data.Segmente.forEach(segmentConfig => {
this.segmenteConfig.push(segmentConfig);
});
});
}
},
created() {
this.loadConfig();
this.loadData('internet');
}
});
My idea is use an <input type="file"> to upload file, then troughth webkitRequestFileSystem save to FileSystem like this...
body.innerHTML = `<input type="file">`;
body.children[0].addEventListener("change", copyFiles);
...
function copyFiles() {
for (var i = 0; i < this.files.length; i++) {
(function (f) {
navigator.webkitPersistentStorage.queryUsageAndQuota(function (usage, granted) {
if ((granted - usage) < f.size) {
navigator.webkitPersistentStorage.requestQuota((granted + f.size), function () {
createFile(f);
}, errorHandler);
} else {
createFile(f);
}
});
})(this.files[i]);
}
}
...
function createFile(file) {
window.webkitRequestFileSystem(window.PERSISTENT, (file.size * 1.1), function (fileManager) {
fileManager.root.getFile(file.name, {create: true, exclusive: true}, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.write(file);
}, errorHandler);
}, errorHandler);
}, errorHandler);
}
And it works, now I want use service worker to read and send little packets of contents of these files to my backend.
I'm new on Service Workers and I tried but I got self.webkitRequestFileSystem is not a function
Service Worker activation...
window.addEventListener("load", function () {
if ('serviceWorker' in navigator) {
window.addEventListener("message", function(e){
console.log(e);
});
navigator.serviceWorker.register('js/swa.js').then(function (swr) {
swr.sync.register('syncTest');
}).catch(function (error) {
console.log(error);
});
} else {
console.log("Service Worker", "Not available.");
}
});
And ServiceWorker script
function getAllEntries(dirReader) {
var entries = dirReader.readEntries();
for (var i = 0, entry; entry = entries[i]; ++i) {
paths.push(entry.toURL()); // Stash this entry's filesystem: URL.
// If this is a directory, we have more traversing to do.
if (entry.isDirectory) {
getAllEntries(entry.createReader());
}
}
}
self.addEventListener('sync', function (event) {
try {
var fs = self.webkitRequestFileSystem(self.PERSISTENT, 1024 * 1024 /*1MB*/);
getAllEntries(fs.root.createReader());
self.postMessage({entries: paths});
} catch (e) {
console.log(e);
}
});
I am trying to append the new object in the for loop to the request JSON.
this is not working :
setCapabilities('default',['1','2','3'])
export function
setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]){
var request:object = {
type:'setCapabilities',
kaiId:kaiId
};
capabilitiesArr.forEach(element => {
var obj = {
element:true
}
console.log(obj)
});
}
This is also not working :
export function setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]){
var request:object = {
type:'setCapabilities',
kaiId:kaiId
};
capabilitiesArr.forEach(element => {
var obj[element]=true
console.log(obj)
});
}
I want the output to be as :
console.log(request)
{
type:'setCapabilities',
kaiId:'default',
'1':true,
'2':true,
'3':true
}
I've updated the code in javascript for browser to run the code snippet, but you can convert it to typescript for your use
function setCapabilities(kaiId, capabilitiesArr) {
var request = {
type: 'setCapabilities',
kaiId: kaiId
}
var obj = Object.assign({}, request)
capabilitiesArr.forEach(element => {
obj[element] = true
});
console.log(obj)
}
setCapabilities('default',['1','2','3'])
In typescript use below code
function setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]) {
var request:object = {
type: 'setCapabilities',
kaiId: kaiId
}
var obj = {...request}
capabilitiesArr.forEach(element => {
obj[element] = true
});
console.log(obj)
}
I am new in nodejs and I want to make a json array by comparing id inside a loop but the MongoDB function does not wait for the loop to complete, so data is not coming out properly. It displays the data before the loop ends, below is the code:
router.get('/getallcountrydataup',function(req, res) {
Country
.where('isDeleted').equals(false)
.exec(function(err,cData){
if (!cData) {
res.json({'status':0,'message': 'No data found','data':[]});
} else{
async.waterfall([
function (done) {
var countryalldata = [];
for (var i = 0; i < cData.length; i++) {
var country_s = cData[i];
State.where('s_c_id').equals(country_s._id)
.exec(function(err, statedata){
country_s.statecount = statedata.length;
//console.log(country_s._id);
console.log(country_s.statecount);
});
countryalldata.push(country_s);
}
done(err, countryalldata);
// console.log(countryalldata);
},
function (countryalldata, done) {
console.log(countryalldata);
res.json({
'status': 1,
'message': 'Data found',
'data': countryalldata
});
}
]);
}
});
});
Here is output of the countryalldata variable printed before the loop will complete. I want to print its output after loop execution is complete.
State.where is asynchronous so it should be synchronized. For example with async.map
router.get('/getallcountrydataup',function(req, res) {
Country
.where('isDeleted').equals(false)
.exec(function(err,cData){
if (!cData) {
res.json({'status':0,'message': 'No data found','data':[]});
} else {
async.waterfall([
function (done) {
async.map(cData, function (country_s, done2) {
// Convert country_s into plain object. It's not a mongoose
// model anymore
country_s = country_s.toObject();
State.where('s_c_id')
.equals(country_s._id)
.exec(function(err,statedata){
if (err) {
done2(err);
return;
}
country_s.statecount = statedata.length;
console.log(country_s.statecount);
done2(null, country_s)
});
}, function(err, countryalldata) {
if (err) {
done(err);
}
else {
done(null, countryalldata)
}
});
},
function (countryalldata, done) {
console.log(countryalldata);
res.json({'status':1,'message': 'Data found','data':countryalldata});
}
]);
}
});
});
I'am using below code to get data from a collection
Marketing.find({
shopId: req.params.shopId,
locationId: req.params.locationId,
}).exec(function (err, campaigns) {
if (err) {
return next(err);
} else if (!campaigns) {
return next(new Error('Failed to load Campaigns '+ req.params.shopId));
}
I want to make a api call on campaigns object i use the below code
campaigns.forEach(function(item) {
async.waterfall([
function (done) {
item.opens = "-";
item.requests = "-";
var currentDate = new Date();
var formatedDate = currentDate.toISOString().slice(0,10);
var request = sg.emptyRequest();
request.queryParams.aggregated_by = 'day';
request.queryParams.limit = '1';
request.queryParams.start_date = '2016-01-01';
request.queryParams.end_date = formatedDate;
request.queryParams.offset = '1';
request.queryParams.categories = item._id;
request.method = 'GET';
request.path = '/v3/categories/stats';
sg.API(request, function (response) {
response.body = JSON.parse(response.body);
done(err,response.body)
});
},
function (data,done) {
for(var i=0;i<data.length;i++){
unique_opens = parseInt(unique_opens)+parseInt(data[i].stats[0].metrics.unique_opens);
opens = parseInt(opens)+parseInt(data[i].stats[0].metrics.opens);
requests = parseInt(requests)+parseInt(data[i].stats[0].metrics.requests);
}
if(unique_opens>=1 && requests>=1){
item.clickrate = (unique_opens/opens)*100;
}
else{
item.clickrate = 0;
}
item.opens = opens;
item.requests = requests;
console.log(item.opens);
opens = 0;
unique_opens = 0;
requests = 0;
console.log(item);
},
], function (error) {
if (error) {
//handle readFile error or processFile error here
}
});
});
And at the end i do
res.json(campaigns);
But it doesn't add the two new keys in each index [ opens & request ]
Use map() as follows:
Marketing.find({
shopId: req.params.shopId,
locationId: req.params.locationId,
}).lean().exec(function (err, campaigns) {
if (err) {
return next(err);
} else if (!campaigns) {
return next(new Error('Failed to load Campaigns '+ req.params.shopId));
}
campaigns = campaigns.map(function(item){
return {
opens: 'SOMELOGIC',
requests: 'SOMELOGIC',
opens: item.opens,
requests: item.requests,
};
});
res.json(campaigns);
}