Consider I have an object A having pointer to object B.
Object B has a property "title" in it.
I want to query on object A with a string which is contained in title of object B.
Something like
var query1 = new Parse.Query("objectA");
query1.include("objectB");
query1.contains("objectB.title", anyQuery);
query.find({
success: function(obj){
},
error: function(obj, error) {
}
});
"anyQuery" here can be any string entered by a user in search field. Consider a user inputs "Mary" as query I should get all objectA related to objectB having title containing "Mary" in it. For example "Maryland".
Basically in simple words I want to execute a like query on related data in parse.
Edit
Thank you for the reply. I read the documentation at https://parse.com/docs/js_guide#queries-relational. I would like to extend my question. I want to use the query formed by matchesQuery in an or condition what I have done in my code is below but I get no results:
if(filterQuery) {
var Organization = Parse.Object.extend("Organization");
//LIKE QUERIES
var nameLikeQuery = new Parse.Query(Parse.User);
nameLikeQuery.contains("nameLc", filterQuery);
var phoneLikeQuery = new Parse.Query(Parse.User);
phoneLikeQuery.contains("phone", filterQuery);
var emailLikeQuery = new Parse.Query(Parse.User);
emailLikeQuery.contains("username", filterQuery);
var organizationMatchQuery = new Parse.Query(Organization);
organizationMatchQuery.contains("titleLc", filterQuery);
var userOrganizationQuery = new Parse.Query(Parse.User);
userOrganizationQuery.matchesQuery("organization", organizationMatchQuery);
var userQuery1 = new Parse.Query.or(nameLikeQuery, phoneLikeQuery);
var userQuery2 = new Parse.Query.or(emailLikeQuery, userQuery1);
userQuery = new Parse.Query.or(userQuery2, userOrganizationQuery);
} else {
userQuery = new Parse.Query(Parse.User);
}
if(type != "ALL") {
userQuery.equalTo("userType", type);
}
userQuery.include("organization");
userQuery.descending("createdAt");
userQuery.find();
As stated by Chris, this scenario is well documented under Relational Queries here:
https://parse.com/docs/js_guide#queries-relational
So for your particular needs it would look like:
var objectBQuery = new Parse.Query("objectB");
objectBQuery.contains("title", anyString);
var objectAQuery = new Parse.Query("objectA");
objectAQuery.matchesQuery("objectB", objectBQuery);
objectAQuery.find().then(function (list) {
// use list
}, function (error) {
console.log(error);
});
Related
Could someone tell me how to push elements into an array in localStorage?
My code:
(localStorage.getItem('projects') === null) ? localStorage.setItem('projects', ['proj1', 'proj2', 'proj3']) : '';
var ItemGet = localStorage.getItem('projects');
function CreateObject() {
console.log(ItemGet);
var Serializable = JSON.parse(ItemGet);
Serializable.push('proj4');
console.log(ItemGet);
}
<button onclick="CreateObject()">Add Object</button>
General approach:
let old_data = JSON.parse(localStorage.getItem('projects'))
let new_data = old_data.push(some_new_data)
localStorage.setItem('projects',JSON.stringify(new_data))
I would do the following assuming that your data is not a multiDimensional array.
(localStorage.getItem('projects') === null) ? localStorage.setItem('projects',
JSON.stringify(['proj1', 'proj2', 'proj3'])) : '';
var ItemGet = localStorage.getItem('projects');
function CreateObject() {
var Serializable = JSON.parse(ItemGet);
Serializable.push('proj4');
localStorage.setItem('projects',JSON.stringify(Serializable));
}
The problem you are hitting is that data stored in localStorage has to be a string. You'll have to parse/stringify before settting/getting anything from local storage. If you didn't want to work with strings, you may find something like IndexedDB API
const stuff = [ 1, 2, 3 ];
// Stringify it before setting it
localStorage.setItem('stuff', JSON.stringify(stuff));
// Parse it after getting it
JSON.parse(localStorage.getItem('stuff'));
Here is an example of using IndexedDB API from the docs
const dbName = "the_name";
var request = indexedDB.open(dbName, 2);
request.onerror = function(event) {
// Handle errors.
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
// Create an objectStore to hold information about our customers. We're
// going to use "ssn" as our key path because it's guaranteed to be
// unique - or at least that's what I was told during the kickoff meeting.
var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
// Create an index to search customers by name. We may have duplicates
// so we can't use a unique index.
objectStore.createIndex("name", "name", { unique: false });
// Create an index to search customers by email. We want to ensure that
// no two customers have the same email, so use a unique index.
objectStore.createIndex("email", "email", { unique: true });
// Use transaction oncomplete to make sure the objectStore creation is
// finished before adding data into it.
objectStore.transaction.oncomplete = function(event) {
// Store values in the newly created objectStore.
var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers");
customerData.forEach(function(customer) {
customerObjectStore.add(customer);
});
};
};
There are also other solutions out there like PouchDB depending on your needs
Say for example you have an array. This is how you can store it in the local storage.
let my_array = [1, 2, 3, 4];
localStorage.setItem('local_val', JSON.stringify(my_array))
Now to push any data into the local storage array you have to override by the new data like bellow
let oldArray = JSON.parse(localStorage.getItem('local_val'))
oldArray.push(1000)
localStorage.setItem('local_val', JSON.stringify(oldArray))
I'm using firebase to make a chat application. I stumbled upon a little problem.
When making requests to the firebase database, firebase will return a JSON or JS object back (I'm new to this so I don't really know).
This is the structure of my database:
The first ID under the message tree is the client's ID which I get when a cidst connects to the application. The id's just below are the client'ID with whom the logged client chatted with and the Id below that is firebase generated ID for each message.
With this code (see below) I'm listening on the database to see if any messages have been added for notification purposes.
var ref = database.ref('messages/81k44hlET5cq2AorxLDxD1DeXV52/');
ref.on('value', gotData, errData);
function gotData(data) {
var msgs = data.val();
var keys = Object.keys(msgs);
console.log(msgs);
messages = new Array();
timestamp = new Array();
type = new Array();
for(var keys in msgs) {
if (msgs.hasOwnProperty(keys)) {
console.log(keys + " -> " + msgs[keys]);
messages.push(msgs[keys]);
}
}
}
The output of the code:
I'm getting an array with two objects. Until here everything works fine.
My problem is that I can't figure out how I can get my message properties from here using JavaScript since the Message-IDs are unknown.
What I mean is that I can't access the properties doing msgs[keys].id.message for example since ID is unknown.
var ref = database.ref('messages/81k44hlET5cq2AorxLDxD1DeXV52/');
ref.on('value', gotData, errData);
function gotData(data)
{
var msgs = data.val();
var keys = Object.keys(msgs);
console.log(msgs);
messages = new Array();
timestamp = new Array();
type = new Array();
for(var keys in msgs)
{
if (msgs.hasOwnProperty(keys)) {
console.log(keys , " -> " , msgs[keys]);
messages.push(msgs[keys]);
var k = msgs[keys];
for(var keys in k){
console.log( k[keys]);
}
//
}
}
You could iterate over your JavaScript object with the .forEach method, use Object.entries for this.
In the following code snippet, I am logging all message objects
const messages = {
kjzn5ef6ke2zlfzn: {
h6qjopdbgs5d6mv7f: {
gd73g4d5d9dvtjzj15: {
message: "k",
seend: "true",
timestamp: "26/6/2018 20",
type: "send"
},
kdaz8bamd6kprmq78: {
message: "k",
seend: "true",
timestamp: "26/6/2018 20",
type: "send"
}
}
}
};
Object.entries(messages).forEach(([id1, a]) => {
Object.entries(a).forEach(([id11, b]) => {
Object.entries(b).forEach(([id111, message]) => {
console.log(id1, '=>', id11, '=>', id111, ':', message)
});
});
});
So far I can retrieve the list based on a string I pass and even the column names but I can't figure out how to get the values of a specific column. Here is what I have so far.
function GetFieldList()
{
var listname = document.getElementById("ListName").value;
var ctx = SP.ClientContext.get_current();
this.web = ctx.get_web();
ctx.load(this.web);
this.list = web.get_lists().getByTitle(listname);
ctx.load(this.list);
this.fields = this.list.get_fields();
ctx.load(this.fields);
ctx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
Btw I'm using SharePoint 2010.
I think your code is not full the client Context must run async method to load the values
If you want correct way to get the values from SharePoint read the this documentation :
https://msdn.microsoft.com/en-us/library/office/hh185007(v=office.14).aspx
or you can use another library such as rest api or spservice .
Anyway the get_fields() return the fields list name not values.
As you said SP.ClientContext.get_current(); is an Javascript Object, so first of all you need to check if the property that you want to know if is null or empty, exists.
var ctx = SP.ClientContext.get_current();
isPropertyEmptyOrNull = ctx.hasOwnProperty('myProperty') && (prop.myProperty === null or prop.myProperty === '' or prop.myProperty === undefined)
You found more details abour hasOwnProperty here
Refer below code. This shows how to retrieve items from SharePoint list.
function GetItems() {
var context = new SP.ClientContext.get_current();
var list = context.get_web().get_lists().getByTitle('ListName');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("");
collItems = list.getItems(camlQuery);
context.load(collItems);
context.executeQueryAsync(GetItemsSuccess, GetItemsFail);
}
function GetItemsSuccess() {
var listItemEnumerator = collItems.getEnumerator();
if (collItems.get_count() > 0) {
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
/*
retrieve specific fields (e.g. Title, FirstName...)
Here 'Title' and 'FirstName' will be the internal name of the field you want to retrieve
*/
var title = oListItem.get_item('Title');
var firstName = oListItem.get_item('FirstName');
}
}
}
function GetItemsFail(sender, args) {
// Error handler code
}
I want to retrieve tweets and mentions from the twitter api. After doing this I want gather the tweets and mentions and store it in one json array. So far when I store both tweets and mentions, the system replaces the tweets in the object with the mentions?
jsonx = {};
var tweets = function(){
client.get('search/tweets', {q:"#"+string.teamname, count:1},
function (err,data){
for(var index in data.statuses){
var tweet = data.statuses[index];
jsonx[index] = tweet
}
})
}
var mentions = function(){
client.get('statuses/user_timeline', {screen_name:"#"+string.teamname, count:1},
function(err,data) {
for(var index in data){
var tweet = data[index];
jsonx[index] = tweet
}
})
}
var doSometing = function(tweets, mentions){
if (string.checktweet1 == 'on'){
tweets()
}
if (string.checkmentions1 == 'on'){
mentions()
}
}
doSometing(tweets,mentions)
Look into Object.assign() which is like merging to Objects (but in reality it creates a new Object). If you combine it with Array.concat, you can do something like this...
let jsonx = {
tweets: [],
mentions: []
};
// ....
let tweet = data.statuses[index];
jsonx = Object.assign({}, jsonx, {
tweets: jsonx.tweets.concat([tweet])
});
Your example involves mutation which is undesirable and leads to your mentions overriding tweets. This example is constantly creating a new object based on old data (same with Array.concat which creates a new array).
I want to retrieve two objects with title cc and bb above.
My code:
var Item = Parse.Object.extend('Item');
var query = new Parse.Query(Item);
query.notEqualTo('parentItem',undefined);
query.find().then(function(subItems){
console.log(subItems);
},function(error){
console.log(error.code+': '+error.message);
});
The error is 102: pointer field parentItem needs a pointer value
Any help is really appreciate.
Use Parse.Query.exists(key)
var Item = Parse.Object.extend('Item');
var query = new Parse.Query(Item);
query.exists('parentItem');
query.find().then(function(subItems){
console.log(subItems);
},function(error){
console.log(`${error.code}: ${error.message}`;
});
Change undefined to null and it will work
var Item = Parse.Object.extend('Item');
var query = new Parse.Query(Item);
query.notEqualTo('parentItem',null);
query.find().then(function(subItems){
console.log(subItems);
},function(error){
console.log(error.code+': '+error.message);
});