I have created one Azure function in Azure app which is triggered by IOT Hub, and it saves received messages in SQL database. but it is not able to handle when it receives multiple messages. my function is bellow.
module.exports = function (context, iotHubMessage) {
for (var i = 0; i < iotHubMessage.length; i++) {
var iotMsgObj = iotHubMessage[i];
context.log('Message : ' + JSON.stringify(iotMsgObj));
context.bindings.paraSession = JSON.stringify(iotMsgObj); //to save data in SQL database
context.done(); // will save first message only
}
// context.done(); // will save last message only
};
when iotHubMessage hub has multiple JSON objects, it will save ether first or last message from iotHubMessage will store in database table.
please advice what I am doing wrong?
I haven't tried with SQL binding, but returning an array works for other types (e.g. queue):
module.exports = function (context, iotHubMessage) {
context.bindings.paraSession = [];
for (var i = 0; i < iotHubMessage.length; i++) {
var iotMsgObj = iotHubMessage[i];
context.bindings.paraSession.push(JSON.stringify(iotMsgObj));
}
context.done();
};
Mikhail is right if you are storing data in Azure Table Storage. But when you are using SQL Database you need the following code snippet.
module.exports = function (context, iotHubMessage) {
var tempArr = [];
for (var i = 0; i < iotHubMessage.length; i++) {
var iotMsgObj = iotHubMessage[i];
tempArr.push(iotMsgObj);
}
context.bindings.paraSession = tempArr;
context.done();
};
Related
I'm using MongoDB for the first time and having some difficulty. I'm trying to get an object from the database and then set properties of this object to be other objects in the database.
app.get('/photoCollection/:id', function (request, response) {
var id = request.params.id;
var query = Photos.find({user_id: id});
query.select("_id user_id comments file_name date_time").exec(function(err, info) {
if (info === null) {
console.error('Photos for user with _id:' + id + ' not found.');
response.status(400).send('Not found');
}
infoParsed = JSON.parse(JSON.stringify(info));
for (let i = 0; i < infoParsed.length; i++) {
for (let j = 0; j < infoParsed[i].comments.length; j++) {
let commenter_id = infoParsed[i].comments[j].user_id;
delete infoParsed[i].comments[j].user_id;
let commenterQuery = User.findOne({_id: commenter_id});
let commenter;
commenterQuery.select("_id first_name last_name").exec(function(err, info) {
commenter = info;
});
infoParsed[i].comments[j].user = commenter;
}
}
response.status(200).send(infoParsed);
});
});
I've tried this a few ways, and with this way (my most recent try), I'm getting the commenter is undefined. I haven't seen queries used like this, so I'm not surprised, but I was wondering if there was a better way to get something from the database during a query. Any help would be appreciated!
I am beginner in express js, i made api for my music app from express and firebase, that takes data from firebase and takes request and send data as response. But there is problem which is messing the program. Each time the value (Views of music) of firebase changes it re sends the same response.
heres my code
app.use(cors())
let trendingTracks = []
let data;
function Trending(data){
if (data){
Object.values(data).forEach((value)=>{
if(value.views < 10){
trendingTracks.push(value)
}
})
}
}
function SortPopular(a){
for(let i = 0; i<=a.length; i++){
for (let j = i+1; j<a.length; j++){
if(a[i].views>a[j].views){
const temp = a[i]
a[i]=a[j]
a[j]=temp
}
}
}
return a
}
firebase.database().ref("public/songs").on("value", snapshot =>{
data = snapshot.val();
Trending(data)
})
app.get("/api/home/trending", (req, res)=>{
res.send(SortPopular(trendingTracks))
})
app.listen(4000, ()=>console.log("listening at port 4000..."))
This is what my database looks like:
And each time views value changes it re response the same data.
When the value of database is not changed:
When the value of database is changed:
As you can see the same thing re sends.
I do not see your whole code, so I cannot be 100% sure, but I suspect it happens because you are constantly adding items to trendingTracks, but need to actually clear it every time you run Trending function.
So add trendingTracks = [] as in here:
app.use(cors())
let trendingTracks = []
let data;
function Trending(data){
if (data){
trendingTracks = [] // NEW
Object.values(data).forEach((value)=>{
if(value.views < 10){
trendingTracks.push(value)
}
})
}
}
function SortPopular(a){
for(let i = 0; i<=a.length; i++){
for (let j = i+1; j<a.length; j++){
if(a[i].views>a[j].views){
const temp = a[i]
a[i]=a[j]
a[j]=temp
}
}
}
return a
}
firebase.database().ref("public/songs").on("value", snapshot =>{
data = snapshot.val();
Trending(data)
})
app.get("/api/home/trending", (req, res)=>{
res.send(SortPopular(trendingTracks))
})
I am building ATM project and storing user data in local storage but after then I collect data and loop on this to match an existing user or creating a new user the data I can get is not be able to convert on JSON
after getting data from local storage I can't be able to convert to JSON for looping the data.
function User(id,pin,amount) {
this.id = id,
this.pin = pin,
this.amount = amount
}
var memory = [];
function loginSignup(){
var id= document.querySelector('.card').value;
var pin= document.querySelector('.pass').value;
var user = new User(id,pin);
user = JSON.stringify(user);
memory.push(user);
localStorage.setItem('user', memory);
var localData = [];
localData.push(localStorage.getItem('user'));
console.log(localData);
}
for(var i=0; i<localstorage.length; i++){
if(localstorage[i].id == id){
only allow update }
else{ update new user}
Like this is for understanding I want to loop in local storage data that users enter.
You need to use JSON.stringify while saving user data into storage:
localStorage.setItem('user', JSON.stringify(memory));
Now, whenever you need you can get the array back which will be parseable and traverseable:
var data = window.localStorage.getItem('user');
if (data) {
data = JSON.parse(data);
for (var i=0; i< data.length; i++) {
if (JSON.parse(data[i]).id == id) { // see note below
console.log("matched user", data[i])
}
else {
console.log("other user:", data[i])
}
}
}
Note; down the tree you also need to parse user-data array elements eg. JSON.parse(data[i]) because you have stringified that before pushing into memory array.
DEMO https://jsfiddle.net/pg2bsLve/1/
I am learning about Node and Feathers on a job. Need to make a simple app that would use feathers to load the [nedb] with sample data.
var fake = require('./fake.js');
var feathers = require('feathers-client');
var io = require('socket.io-client');
var socket = io("http://127.0.0.1:8000");
var app = feathers()
.configure(feathers.socketio(socket));
var accountsAPIService = app.service('/api/accounts');
var dummyData = fake();
// import dummy data
for ( var i = 0; i < dummyData.accounts.length; i++) {
// console.log(dummyData.accounts[i]);
var params = { query: {}};
accountsAPIService.create(dummyData.accounts[i], params).then(function(account) {
console.log("inserted: ", account);
});
}
// read back inserted records
accountsAPIService.find(params, function(accounts) {
console.log("accounts: ", accounts);
});
i just need to insert items from the array dummyData.accounts into the server.
When I run the script, it seems that nothing is being imported.
When I read the records back, it returns:
accounts: null
What is the proper way of inserting/creating records with Feathers?
Could not figure out how to use ".then" so used a regular form:
for ( var i = 0; i < dummyData.accounts.length; i++) {
var params = { query: {}};
accountsAPIService.create(dummyData.accounts[i], params, function(error, account) {
// console.log("inserted: ", account);
});
}
That works fine.
To read the data back, I corrected the method signature. Then, it works. :)
accountsAPIService.find(function(error, accounts) {
console.log("accounts: ", accounts);
});
Basically I'm making a nice and simple mobile web app for a couple of my friends. It uses some online databases to store position data of shops. I've got the databases working like a charm. No problems there. In fact everything is working except it's all happening in the wrong order I think. The data from the database should be stored in an array and then the objects in that array are displayed on screen. However, using some console logs I've found that the data is being displayed, then being retrieved from the database, then the arrays are filled. But no matter what I do, I can't get it to work! Here is my code:
var latOfSpots;
var lngOfSpots;
var nameOfSpots;
var spotArray;
var spotLatLng;
var spotCollection;
var markers;
var Spot;
var spot;
function init() {
//-------------------------- INITIATE SPOT VARIABLES ---------------------------//
map = new google.maps.Map2(document.getElementById("map"));
latOfSpots= new Array(51.14400,51.02295);
lngOfSpots= new Array(0.25721,0.26450);
nameOfSpots= new Array('Tescos', 'Sainsburys');
spotLatLng= new Array();
markers= new Array();
Spot = Parse.Object.extend("Spot");
spot = new Spot();
//----------------- GET DATA FROM THE PARSE.COM DATABASE ---------------------//
//---------------------- DISPLAY ARRAY DATA ON MAP ---------------------------//
GetData();
DisplayData();
//----------------------- SET MAP SETTINGS -----------------------------------//
map.setCenter(spotLatLng[0],8);
//map.addControl(new google.maps.LargeMapControl());
map.addControl(new google.maps.MapTypeControl());
}; //END OF INIT FUNCTION ------------------------------------------------//
google.setOnLoadCallback(init);
//------------------- PRIMARY FUNCTION TO GET DATA FROM DATABASE ---------------//
function GetData()
{
var query = new Parse.Query(Spot);
spotCollection = query.collection();
spotCollection.fetch({
success: function(spotCollection) {
// spotCollection.toJSON()
// will now be an array of objects based on the query
FillArrays();
console.log('data retreived' + spotCollection);
}
});
}
//----------------- FUNCTION TO LOAD DATABASE INTO ARRAYS -------------------//
function FillArrays()
{
spotArray = spotCollection.toJSON();
for (var j = 0; j<spotArray.length; j++)
{
latOfSpots.push(spotArray[j].Latitude);
lngOfSpots.push(spotArray[j].Longitude);
nameOfSpots.push(spotArray[j].Name);
}
}
//------------------------ FUNCTION TO DISPLAY ALL ARRAY DATA ONSCREEN -----------------//
function DisplayData()
{
for(var i = 0; i<latOfSpots.length; i++)
{
spotLatLng[i] = new google.maps.LatLng(latOfSpots[i], lngOfSpots[i]);
for(var x = 0; x<latOfSpots.length; x++)
{
markers[x] = new google.maps.Marker(
spotLatLng[i], {
"draggable":false,
"title":nameOfSpots[i],
});
map.addOverlay(markers[x]);
}
}
console.log('data displayed');
}
Your database query is asynchronous. You need to use the data in the Get_Data callback function (after it has come back from the server). Currently you are attempting to use it before the server sends it back.
//------------------- PRIMARY FUNCTION TO GET DATA FROM DATABASE ---------------//
function GetData()
{
var query = new Parse.Query(Spot);
spotCollection = query.collection();
spotCollection.fetch({
success: function(spotCollection) {
// spotCollection.toJSON()
// will now be an array of objects based on the query
FillArrays();
console.log('data retreived' + spotCollection);
DisplayData();
}
});
}