Search Firebase Database using key with search bar - ios

I have data in firebase database and the data is structured as shown in the attached image. I am trying to search using search bar to look for the name of recipe(s) when user enter search query in the app. Indexing rules currently set also shown in the attached image. Here is my code:
self.findRecipes(text: "Lemon")
func findRecipes(text: String)->Void{
ref.child("Categories").queryOrdered(byChild: "recipeName").queryStarting(atValue: text).queryEnding(atValue: text+"\u{f8ff}").observe(.value, with: { snapshot in
print(snapshot)
})
}
The output in the console is
Snap (Categories) <null>
Any help?

Sorry, I only know how to retrieve data successfully using search bar from firestore DB in webapps. May be it can help you.
HTML:
<input type="text" placeholder="search" id="latestHotDogStatus">
<ul id="pastComments2"></ul>
<li><id="loadButton">Search</li>
JS:
firebase.initializeApp(config);
var firestore = firebase.firestore();
var docRef = firestore.collection("indian");
var showat2 = document.querySelector("#pastComments2");
var loadbutton = document.querySelector("#loadButton");
var inputTextField = document.querySelector("#latestHotDogStatus");
loadbutton.addEventListener("click",function(){
docRef.get()
.then(snapshot => {
snapshot.forEach(doc => {
const myData = doc.data();
if(myData.dname == inputTextField.value){
showat2.innerHTML += myData.dname+" "+myData.dno+myData.no+ ;
inputTextField.innerHTML = " ";
}
});
}).catch(function(error){
console.log("error: "+error);
});
});

Related

Ionic v1 /Angular JS slow rendering views when use Sqlite plugin

I developing an application using ionic1 and AngularJS.When i want to go back to previous view i must save some data into sqlite database using sqlite plugin from https://github.com/litehelpers/Cordova-sqlite-storage.git.When i press button to go back i see a lag when it pass from a view to another.The sqlite table structure have two columns:
->Id -primary key -integer
->data-string
In this table i want to save data field as string(from json).
Does anyone knows how to make this process faster? I'm using an iPad for testing.
I'm posting my code here to show how save function is implemented.Thanks for any help. :)
$scope.storeProfileDataCourses = function(data) {
console.log('insertData');
var querySelect = "SELECT * FROM Table where Id=?";
$cordovaSQLite.execute(db, querySelect, [crewId]).then(function(res) {
console.log('Rows:' + res.rows.length);
if (res.rows.length > 0) {
var queryUpdate = "UPDATE Table SET data=? WHERE Id=?";
$cordovaSQLite.execute(db, queryUpdate, [JSON.stringify(data), crewId]).then(function(res) {
console.log('update');
console.log(res);
}, function(err) {
console.error(err);
});
} else {
console.log('Need to insert');
var query = "INSERT INTO Table(Id,data) VALUES (?,?)";
$cordovaSQLite.execute(db, query, [Id, JSON.stringify(data)]).then(function(res) {
console.log("INSERT ID -> " + res.insertId);
}, function(err) {
console.error(err);
});
}
});
}

How do I tie an image stored in Firebase Storage to a record in Firebase Database? *SWIFT/iOS* [duplicate]

I have a marketplace web app, where users can upload items, and of course they can also see images associated with these items. The problem is organizing the storage buckets, I was thinking to make the path itemImages/itemUID/image1.jpg. The problem is getting the itemUID, which is automatically generated, after an item is added to the database.
Here's a code snippet I have for adding items to the db:
itemsRef.push({
title: title,
description: description,
tags: tags,
price: price,
});
and here's a simplified function I use to store an image:
var uploadTask = imageNewItemRef.child('fakeUID' + '/' + imageNames[x]).putString(images[x], 'base64');
uploadTask.on('state_changed', function(snapshot) {
}, function(error) {
console.log("error uploading image");
}, function() {
var downloadURL = uploadTask.snapshot.downloadURL;
console.log(downloadURL);
});
as you can see, I'm using a hardcoded fakeUID link for testing purposes, but I have no clue (and searching hasn't helped), on how to have a uniqueUID instead of a fake one, that is linked to the item :/
Any help is appreciated!
Apologies for poorly written (and untested) JS, but would something like this work?
// create a new push ID and update the DB with some information
var currentItemRef = itemsRef.push({
title: title,
description: description,
tags: tags,
price: price,
}).then(function() {
var storageRef = firebase.storage().ref();
// currentItemRef.name is the unique key from the DB
return storageRef.child(currentItemRef.name + '/' + imageNames[x]).putString(images[x], 'base64');
}).then(function(snapshot) {
// update the DB with the download URL
return currentItemRef.update({
url: snapshot.metadata.downloadURLs[0]
});
}).catch(function(error) {
console.error(error);
});

Webix mobile calendar saving events to mysql database twice

So am experimenting with Webix and so far I like it. Am playing around with the mobile calendar/scheduler and am getting stuck with saving new events into mysql database. I have followed the tutorials and docs about saving data to the database and indeed I am able to save new events. Problem is that it is saving the new events twice, and I have failed to figure out why. Here is the code:
webix.ready(function(){
webix.ui.fullScreen();
webix.ui({
rows:[
{
view: "toolbar", id:"toolbar", elements:[
{
view: "icon", icon: "bars",
click: function(){
if( $$("menu").config.hidden){
$$("menu").show();
}
else
$$("menu").hide();
}
},
{
view: "label",
label: "JPlan"
}
]
},
{
view: "scheduler",
id: "scheduler",
url: "data/getEvents.php",
save:{
"insert":"data/saveEvents.php",
"update":"data/update.php",
"delete":"data/delete.php"
}
}
]
});
});
And the php code to save the new events:
<?php
include('mysql.class.php');
$db = new MySQL();
$values = array();
$now = time();
$values["eventTitle"] = MySQL::SQLValue($_POST['text']);
$values["eventJudge"] = MySQL::SQLValue($_POST['judge']);
$values["eventStart"] = MySQL::SQLValue($_POST['start_date']);
$values["eventEnd"] = MySQL::SQLValue($_POST['end_date']);
$values["eventNotes"] = MySQL::SQLValue($_POST['details']);
$values["eventAddedTime"] = MySQL::SQLValue($now);
$values["eventAddedBy"] = MySQL::SQLValue('');
// Execute the insert
$result = $db->InsertRow("tbl_events", $values);
?>
The app loads all events from the database well. It is just that when I save a new event, it saves the evet twice in the database. I have not yet worked on the update and delete code.
Any help?
Client side code expects some valid JSON response from a server-side, as confirmation that the save operation was successful. Otherwise, a client-side code may make another attempt to save a data.
$result = $db->InsertRow("tbl_events", $values);
$id = get_id_of_new_record();
echo "{ id: $id }";

Let user turn off different notification types using parse.com's cloud code

First time posting on here so bear with me. I am taking a dive into parse.com's cloud code without any knowledge of javascript so I could use a little help.
I got an afterSave push notification working with Cloud Code but I need a way to allow users to subscribe/unsubscribe from different types of notifications. The way I am currently attempting to do this is by storing bool values in the parse user table for the different types of notifications but I'm having trouble getting that value in cloud code. Here is my cloud code:
Parse.Cloud.afterSave("Comment", function(request){
var comment = request.object;
var fromUser = request.user;
var onIdea = comment.get("ideaPointer");
var ideaOwner = onIdea.get("owner");
var getNotification = ideaOwner.get("getCommentNotifications");
var message = fromUser.getUsername() + " commented on your idea.";
if (getNotification){
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo("user", ideaOwner);
Parse.Push.send({
where: pushQuery,
data: {
alert: message,
ideaId: onIdea.id
}
});
}
});
Here is the error that gets printed to the logs when a comment is saved:
Result: TypeError: Cannot call method 'get' of undefined at main.js:6:34
Here is the line it is having a problem with because it was working before I added it along with the if statement:
var getNotification = ideaOwner.get("getCommentNotifications");
getCommentNotifications is the bool value in the user table.
I'm also not sure if my if statement is written correctly or not:
if (getNotification){}
I have also verified that getCommentNotifications value for the ideaOwner I'm testing on isn't empty.
Any help with this issue or ideas on a better way to allow users to subscribe/unsubscribe from different notifications types would be much appreciated.
The other ends of the those pointers must be fetched. If they really are pointers, then you can treat them as incompletely initialized objects, so...
Parse.Cloud.afterSave("Comment", function(request){
var comment = request.object;
var fromUser = request.user;
var onIdea = comment.get("ideaPointer");
onIdea.fetch().then(function(onIdeaObject) {
var ideaOwner = onIdea.get("owner");
return ideaOwner.fetch();
}).then(function(ideaOwnerObject) {
var getNotification = ideaOwnerObject.get("getCommentNotifications");
if (getNotification) {
var message = fromUser.getUsername() + " commented on your idea.";
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo("user", ideaOwnerObject);
return Parse.Push.send({ where: pushQuery, data: { alert: message, ideaId: onIdea.id } });
}
});
});

Node CSV Parser output issue

I am trying to use Node CSV Parser to read in a query result from my Mongo database and write it out to a csv file.
When I run my script, I get a csv file with two [object] entries on the first line and everything else blank.
This is my code:
// node samples/sample.js
var csv = require('csv');
var mongoose = require('mongoose');
var User = require('../models/userModel').User;
dsn = "mongodb://localhost/test";
mongoose.connect(dsn);
console.log ("here");
var users = User.find({}, function(err, result){
console.log(result);
});
var columns = ['userName','agencyName','email','password','id'];
csv()
.from(users, {
columns: true
})
.toPath(__dirname+'/users.csv',{
columns: ['userName','agencyName','email','password','id']
})
.transform(function(data){
data.unshift(data.pop());
return data;
})
.on('data',function(data,index){
console.log('#'+index+' '+JSON.stringify(data));
})
.on('end',function(count){
console.log('Number of lines: '+count);
})
.on('error',function(error){
console.log(error.message);
});
This is the data displayed in terminal:
[ { userName: 'LasVegas',
agencyName: 'City of Las Vegas',
email: 'lasvegas#gmail.com',
password: 'upload1',
_id: 4ffe2e6bddc0c02b15000001 } ]
I have only entered one user into the database so I believe it is correct.
Any help would be greatly appreciated!
EDIT:
Here is my code after trying to call csv in the callback:
// node samples/sample.js
var csv = require('csv');
var mongoose = require('mongoose');
var User = require('../models/userModel').User;
dsn = "mongodb://localhost/test";
mongoose.connect(dsn);
console.log ("here");
var columns = ['userName','agencyName','email','password','id'];
var users = User.find({}, function(err, result){
console.log(result);
if (err){
callback(err,null);
}else{
csv()
.from(users, {
columns: true
})
.toPath(__dirname+'/users.csv',{
columns: ['userName','agencyName','email','password','id']
})
.transform(function(data){
data.unshift(data.pop());
return data;
})
.on('data',function(data,index){
console.log('#'+index+' '+JSON.stringify(data));
})
.on('end',function(count){
console.log('Number of lines: '+count);
})
.on('error',function(error){
console.log(error.message);
})
}
});
Now instead of two [object] fields, the fields contain weird symbols and I am asked to choose a filter when opening the file.
Your call to User.find() is asynchronous; it's not assigning the results of the search to users. You need to move your call to csv into the callback and either replace the reference to users there with results or rename the callback parameter to users.

Resources