I am trying to fetch data from mongoDB and store those in array format bot outside of callback function I am getting that array variable as blank using Node.js.
My code is below:
exports.getCardDetails=function(req,res){
var userid=req.body.userid;
var token_id=req.body.token_id;
var userData=[];
db.f_user_login.find({_id: mongoJs.ObjectId(userid),token:token_id},function(err,doc){
if (doc.length > 0) {
db.f_card_details.find({userid:userid},function(errs,docs){
if (!errs) {
if (docs) {
for (var i = 0;i< docs.length;i++) {
var oemail=docs[i].email;
var id=docs[i]._id;
var name=docs[i].name;
var company=docs[i].company;
var position=docs[i].position;
var mobile=docs[i].mobile;
var landline=docs[i].landline;
var url=docs[i].url;
var postcode=docs[i].postcode;
var address=docs[i].address;
var isCurrentUser=docs[i].isCurrentUser;
db.f_user_profile.find({email:oemail},function(errs1,docs1){
if (!errs1) {
if (docs1) {
for(var j=0;j < docs1.length;j++){
var profileText=docs1[j].profiletext;
var biography=docs1[j].biography;
var image=docs1[j].file;
var profileid=docs1[j]._id;
}
var data={"id":id,"name":name,"company":company,"position":position,"mobile":mobile,"email":oemail,"landline":landline,"url":url,"postcode":postcode,"address":address,"profileText":profileText,"biography":biography,"image":image,"isCurrentUser":isCurrentUser,"profile_id":profileid};
userData.push(data);
}
}
})
}
console.log('user',userData);
var sdata={"statusCode": 200,"data":userData ,"message": "Your card details has been fetched successfully"};
res.send(sdata);
}
}
})
}else{
var data={"statusCode": 404,"error": "Not Found","message":"Invalid User"};
res.send(data);
}
})
}
Here I am pushing all data into userData array and trying to send those as response but here my problem is inside the loop all data are pushing to that array but console.log('user',userData); is showing blank while sending those data as response. I need to send those data as response.
userData is filled in db.f_user_profile.find callback, that's where you should move res.send(sdata); as well. Also I suggest to convert to async/await if you are using node7:
exports.getCardDetails = async function(req,res){
var userid=req.body.userid;
var token_id=req.body.token_id;
var userData=[];
const user = await db.f_user_login.find({_id: mongoJs.ObjectId(userid),token:token_id}).next();
if(user) {
const cards = await db.f_card_details.find({userid:userid}).toArray();
for (var i = 0;i < cards.length;i++) {
var email=docs[i].email;
var id=docs[i]._id;
var name=docs[i].name;
var company=docs[i].company;
var position=docs[i].position;
var mobile=docs[i].mobile;
var landline=docs[i].landline;
var url=docs[i].url;
var postcode=docs[i].postcode;
var address=docs[i].address;
var isCurrentUser=docs[i].isCurrentUser;
const profiles = await db.f_user_profile.find({email}).toArray();
for(var j=0; j < profiles.length;j++) {
var profileText=docs1[j].profiletext;
var biography=docs1[j].biography;
var image=docs1[j].file;
var profile_id=docs1[j]._id;
var data={id,name,company,position,mobile,email,landline,url,postcode,address,profileText,biography,image,isCurrentUser,profileid};
userData.push(data)
}
}
console.log('user',userData);
var sdata={"statusCode": 200,"data":userData ,"message": "Your card details has been fetched successfully"};
res.send(sdata);
} else {
var data={"statusCode": 404,"error": "Not Found","message":"Invalid User"};
res.send(data);
}
}
Related
This is my poor code
function loaddata() {
var url = "http://localhost/Geocording/api.php";
$.getJSON(url, function (data) {
var json = data
for (var i = 0, length = json.length; i < length; i++) {
var val = json[i],
var latLng = new google.maps.LatLng(val.lat, val.lng);
console.log(latLng)
}
});
}
Im trying to get details from my own api using json array.
but its not working.
{"location":[{"name":"Home 1","lat":"6.824367","lng":"80.034523","type":"1"},{"name":"Grid Tower 1","lat":"6.82371292","lng":"80.03451942","type":"1"},{"name":"Power Station A","lat":"6.82291793","lng":"80.03417451","type":"1"}],"success":1}
This is json response from my api.php
Try to make things clear first then apply it. First read JSON clearly then go on to apply it in your code. This is the working code.
function loaddata() {
var url = "http://localhost/Geocording/api.php";
$.getJSON(url, function (data) {
var json = data['location'];
for (var i = 0, length = json.length; i < length; i++) {
var val = json[i];
var latLng = new google.maps.LatLng(val['lat'], val['lng']);
console.log(latLng)
}
});
}
Hope this may help you!
I have two array as follows
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
I want to combine these two array and covert it to the following format
var data={
"booktitle":"testtitle",
"bookid":"testid",
"bookauthor":"testauthor"
}
I want to insert this data to database using nodejs
var lastquery= connection.query('INSERT INTO book_tbl SET ?',data, function (error, results, fields) {
if (error) {
res.redirect('/list');
}else{
res.redirect('/list');
}
});
Please help me to solve this.
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
var finalObj = {};
field_array.forEach(function (eachItem, i) {
finalObj[eachItem] = data_array[i];
});
console.log(finalObj); //finalObj contains ur data
You also can use reduce() in a similar way:
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
var result = field_array.reduce((acc, item, i) => {
acc[item] = data_array[i];
return acc;
}, {});
console.log(result);
Here I explaned my code line by line..Hope it will help
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
//Convert above two array into JSON Obj
var jsondata = {};
field_array.forEach(function (eachItem, i) {
jsondata[eachItem] = data_array[i];
});
//End
//Store Jsondata into an array according to Database column structure
var values = [];
for (var i = 0; i < jsondata.length; i++)
values.push([jsondata[i].booktitle, jsondata[i].bookid, jsondata[i].bookauthor]);
//END
//Bulk insert using nested array [ [a,b],[c,d] ] will be flattened to (a,b),(c,d)
connection.query('INSERT INTO book_tbl (booktitle, bookid, bookauthor) VALUES ?', [values], function(err, result) {
if (err) {
res.send('Error');
}
else {
res.send('Success');
}
//END
I am new in firebase and angularjs and i am having difficulties in getting download url from firebase storage and store them in firebase realtime database.
I was able to upload multiple files to firebase storage. the problem is when i store the download url into firebase realtime database, all database url value are same.It should different based each files downloadURL.
Here my script:
$scope.submitPhotos = function(file){
console.log(file);
var updateAlbum = [];
for (var i = 0; i < file.length; i++) {
var storageRef=firebase.storage().ref(albumtitle).child(file[i].name);
var task=storageRef.put(file[i]);
task.on('state_changed', function progress(snapshot){
var percentage=( snapshot.bytesTransferred / snapshot.totalBytes )*100;
if (percentage==100){
storageRef.getDownloadURL().then(function(url) {
var galleryRef = firebase.database().ref('gallery/'+albumkey);
var postkey = firebase.database().ref('gallery/'+albumkey).push().key;
updateAlbum={img:url};
firebase.database().ref('gallery/'+ albumkey+'/'+postkey).update(updateAlbum);
});
};
})
};
};
As you can see i was able store the url into database but all of the urls are same. What i need is every key store each different links from storage.
Any helps appreciated. Thanks
function uploadImg(file,i) {
return new Promise((resolve,reject)=>{
var storageRef=firebase.storage().ref("store-images/"+file[i].file.name);
task = storageRef.put(file[i].file);
task.on('state_changed', function progress(snapshot){
var percentage=( snapshot.bytesTransferred / snapshot.totalBytes )*100;
console.log(percentage);
// use the percentage as you wish, to show progress of an upload for example
}, // use the function below for error handling
function (error) {
console.log(error);
},
function complete () //This function executes after a successful upload
{
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
resolve(downloadURL)
});
});
})
}
async function putImage(file) {
for (var i = 0; i < file.length; i++) {
var dd = await uploadImg(file,i);
firebase.database().ref().child('gallery').push(dd);
}
}
Try using the code below:
$scope.submitPhotos = function(file){
console.log(file);
var updateAlbum = [];
for (var i = 0; i < file.length; i++) {
var storageRef=firebase.storage().ref(albumtitle).child(file[i].name);
var task=storageRef.put(file[i]);
task.on('state_changed', function progress(snapshot)
{
var percentage=( snapshot.bytesTransferred / snapshot.totalBytes )*100;
// use the percentage as you wish, to show progress of an upload for example
}, // use the function below for error handling
function (error) {
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
}, function complete () //This function executes after a successful upload
{
let dwnURL = task.snapshot.downloadURL;
let galleryRef = firebase.database().ref('gallery/'+albumkey);
let postkey = firebase.database().ref('gallery/'+albumkey).push().key;
updateAlbum={img:dwnURL};
firebase.database().ref('gallery/'+ albumkey+'/'+postkey).update(updateAlbum);
});
};
};
All the best!
I'm currently using the angular-file-upload directive, and I'm pretty much using the exact codes from the demo.
I need to add a step in there to test for the dimension of the image, and I am only currently able to do with via jQuery/javascript.
Just wondering if there's a "angular" way to check for the dimension of the image before it's being uploaded?
$scope.uploadImage = function($files) {
$scope.selectedFiles = [];
$scope.progress = [];
if ($scope.upload && $scope.upload.length > 0) {
for (var i = 0; i < $scope.upload.length; i++) {
if ($scope.upload[i] !== null) {
$scope.upload[i].abort();
}
}
}
$scope.upload = [];
$scope.uploadResult = [];
$scope.selectedFiles = $files;
$scope.dataUrls = [];
for ( var j = 0; j < $files.length; j++) {
var $file = $files[j];
if (/*$scope.fileReaderSupported && */$file.type.indexOf('image') > -1) {
var fileReader = new FileReader();
fileReader.readAsDataURL($files[j]);
var loadFile = function(fileReader, index) {
fileReader.onload = function(e) {
$timeout(function() {
$scope.dataUrls[index] = e.target.result;
//------Suggestions?-------//
$('#image-upload-landscape').on('load', function(){
console.log($(this).width());
});
//-------------------------//
});
};
}(fileReader, j);
}
$scope.progress[j] = -1;
if ($scope.uploadRightAway) {
$scope.start(j);
}
}
};
I think you can do it by:
var reader = new FileReader();
reader.onload = onLoadFile;
reader.readAsDataURL(filtItem._file);
function onLoadFile(event) {
var img = new Image();
img.src = event.target.result;
console.log(img.width, img.height)
}
This is the code snippet copied from https://github.com/nervgh/angular-file-upload/blob/master/examples/image-preview/directives.js.
I think this is more angularjs. However, you may need to modify it to fit your requirement.
Try this code
uploader.filters.push({
name: 'asyncFilter',
fn: function(item /*{File|FileLikeObject}*/ , options, deferred) {
setTimeout(deferred.resolve, 1e3);
var reader = new FileReader();
reader.onload = onLoadFile;
reader.readAsDataURL(item);
function onLoadFile(event) {
var img = new Image();
img.onload = function(scope) {
console.log(img.width,img.height);
}
img.src = event.target.result;
}
}
});
i want to put the httpclient in a separate class and want to return the array of founded data.
My Code
function ServiceRequest(callback){
var data = [];
var xhr = Titanium.Network.createHTTPClient({
onload: function(e){
//Ti.API.info("Received text: " + this.responseText);
var doc = this.responseXML.documentElement;
var elements = doc.getElementsByTagName("record");
for (var r=0;r<elements.length;r++){
var name = elements.item(r).getElementsByTagName("field").item(3).textContent;
var monteur = elements.item(r).getElementsByTagName("field").item(15).textContent;
var adresse =elements.item(r).getElementsByTagName("field").item(10).textContent;
var ort = elements.item(r).getElementsByTagName("field").item(4).textContent +" - "+ elements.item(r).getElementsByTagName("field").item(5).textContent;
var date = elements.item(r).getElementsByTagName("field").item(8).textContent;
var termin
if (date !="") {
var arrayDate = date.split(".");
var newdate = arrayDate[1]+"."+arrayDate[0]+"."+arrayDate[2];
var temptermin = newdate +" - "+ elements.item(r).getElementsByTagName("field").item(9).textContent;
termin = temptermin;
};
data.push({"name":name,"monteur":monteur,"adresse":adresse,"ort":ort,"termin":termin});
callback( data );
};
},
onerror: function(e){
Ti.API.debug(e.error);
alert(e.error);
}
});
xhr.open("GET","http://theurltomyxml.com",false);
xhr.send();
}
module.exports =ServiceRequest;
the code snippet for my initialization
var ServiceRequest = require('ui/common/ServiceRequest');
request = new ServiceRequest(function(data){
});
Ti.API.info(request);
But the request is null, the array in my onLoad function is filled with data.
How can i wait until the httpRequest is ready than return the data array ?
You can use your custom function for callback like this way onload : callBack create your own callback function or you can put your callback( data ); after your forloop.
for (var r=0;r<elements.length;r++){//==your code here for parsing
}
callback( data );