Firebase how to Order by child on js - javascript

I can't order a message with timestamp , I tried many ways and it still doesn't work, please help
An arrangement with data like pictures
code
database
data:
{ chatRoom : {
"232": {
"-NKHmBkCihoyRiYABX5O": {
"createdAtDate": "2022-12-27",
"createdAtTime": "17:52:49",
"fromType": 4,
"message": "message2",
"readByAdmin": false,
"readByUser": true,
"timestamp": 1672131169.174558,
"user": "tuan do",
"userId": "232"
}
},
"242": {
"-NKHm6svnBJhWq321aNv": {
"createdAtDate": "2022-12-27",
"createdAtTime": "17:52:29",
"fromType": 3,
"message": "message1",
"readByAdmin": false,
"readByUser": true,
"timestamp": 1672131149.252743,
"user": "solashi 歯科衛生士",
"userId": "242"
}
}
}
}
code : const dbRefAdmin = firebase.database().ref('chatRoom').orderByChild('timestamp').limitToLast(10)

A simple answer :
Try to use "orderBy" instead of "orderByChild"
then "limit" instead of "limitToLast"
Give a feedback in comment and put your post in solved status if the code below solves your problem.
Official documentation : order and limit data with Cloud Firestore
var is_start_load = true;
const dbRefAdmin = firebase.database().ref('chatRoom').orderBy('timestamp').limit(10);

Related

Aggregate specific properties from GitHub API

Instead of getting all properties, I just need to have certain.
This is what I am doing right now, but this way, I am getting a bunch of the properties I don't need:
await fetch(
"https://api.github.com/search/repositories?q=calculator&per_page=100&type=all&language=&sort=stargazers",
{
json: true,
}
).then((res) => res.json())
I need to have only these properties: html_url,
name,
description,
updated_at,
stargazers_count,
forks_count,
id
The GitHub REST API does not provide options for limiting your response, but the GraphQL API does. In your case, your query would look like this:
{
search(query: "calculator", type: REPOSITORY, first: 100) {
edges {
node {
__typename
... on Repository {
id
name
url
description
updatedAt
stargazerCount
forkCount
}
}
}
}
}
You can try it in the explorer: https://docs.github.com/en/graphql/overview/explorer
Sample output:
{
"data": {
"search": {
"edges": [
{
"node": {
"__typename": "Repository",
"id": "MDEwOlJlcG9zaXRvcnkxNjgwMDg3OTc=",
"name": "calculator",
"url": "https://github.com/microsoft/calculator",
"description": "Windows Calculator: A simple yet powerful calculator that ships with Windows",
"updatedAt": "2023-01-19T16:35:31Z",
"stargazerCount": 26550,
"forkCount": 4820
}
}
]
}
}
}

React native - siganlR

I'm having trouble parsing data sent from signalR hub to my client variables.
So heres how it goes,
I activate my signalR listener on my client, and i extract the message like so:
connection.on('StreamData', message => {
// catch message here.
console.log("Message recieved ", message)
});
and i get smth like this:
Message recieved Object {
"Alarms": Array [
Object {
"isActive": true,
"name": "Alarm1",
},
Object {
"isActive": true,
"name": "Alarm2",
},
Object {
"isActive": true,
"name": "Alarm3",
}]
},
"Temperature1": 13,
"Temperature2": 0,
"Temperature3": 0
}
so the thing is i want to pass these parameters and set variables on the clients side, like
clientTemerature1 = message.Temperature1;

How to call FullTextSearchKnowledgeArticle action using REST calls?

How can we call MSCRM action using some HTTP Client request (c#)?
Can any one please assist on this.
The documentation is not covering this action, and I was able to pull this payload from couple of references. But I could not test this in my environment, please test it yourself.
The sample will look like this:
{
"SearchText": "",
"UseInflection": false,
"RemoveDuplicates": false,
"StateCode": 3,
"QueryExpression": {
"#odata.type": "Microsoft.Dynamics.CRM.QueryExpression",
"EntityName": "knowledgearticle",
"ColumnSet": {
"AllColumns": true
},
"Distinct": false,
"NoLock": false,
"PageInfo": {
"PageNumber": 1,
"Count": 10,
"ReturnTotalRecordCount": true,
"PagingCookie": ""
},
"LinkEntities": [],
"Criteria": {
"FilterOperator": "And",
"Conditions": [
{
"EntityName": "knowledgearticle",
"AttributeName": "languagelocaleid",
"Operator": "Equal",
"Values": [
"56940B3E-300F-4070-A559-5A6A4D11A8A3"
]
}
]
}
}
}
Reference.
Make a POST request to the the following URL.
[Your organization root URL]/api/data/v9.1/FullTextSearchKnowledgeArticle
Here is one sample payload that works. You can optionally add additional filters to filter the search result.
{
"SearchText":"test",
"UseInflection":true,
"RemoveDuplicates":true,
"StateCode":3,
"QueryExpression":{
"#odata.type":"Microsoft.Dynamics.CRM.QueryExpression",
"EntityName":"knowledgearticle",
"ColumnSet":{
"AllColumns":true
},
"PageInfo":{
"PageNumber":1,
"Count":10
},
"Orders":[
{
"AttributeName":"modifiedon",
"OrderType":"Descending"
}
]
}
}
Refer the link below for sample code for connecting to Dynamics.
CDSWebApiService class library (C#)

Why is my Mongoose query not updating a value in a nested array in the MongoDB databse?

I have tried to implement this in several ways and none seem to work.
All I need to do is change the Status value of a specific Notifications object (found by its _id) from 0 to 1.
Example JSON:
{
"_id": "577fbf0c7c6e88600ede5e73",
"updatedAt": "2016-07-14T11:27:18.670Z",
"createdAt": "2016-07-08T14:56:12.013Z",
"Name": "Name",
"Email": "test#test.com",
"Notifications": [
{
"_id": "5787644108edec801e9cd0ab",
"Title": "They commented on This",
"Type": 1,
"Status": 0,
"TeamID": "578357109bb105602b1cba27",
"DraftID": "578357b89bb105602b1cba2a"
},
{
"_id": "578777167d1f3424251c361f",
"Title": "He commented on That",
"Type": 1,
"Status": 0,
"TeamID": "578357109bb105602b1cba27",
"DraftID": "578357b89bb105602b1cba2a"
}
]
.....
}
My route:
router.post('/notification', function (req, res) {
UserProfile.update({
'Notifications._id' : req.body.NotificationID
}, {
'$set' : {
'Notifications.$.Status' : 1
}
}, function (err) {
if (err)
res.send(err);
})
});
I don't get any errors and the update doesn't seem to happen.
What could the problem be?
Is the type of Notifications._id ObjectId? If so, try cast req.body.NotificationId to ObjectId. Change the query to
{'Notifications._id' : mongoose.Types.ObjectId(req.body.NotificationID)}
Try '$set' instead of $set.
Ensure that you are getting id coming in correctly.
Update callback comes with updated document - print that to know what happens.
The $ is referring only the first item in the array. If you want to update all you have to use find and save:
UserProfile.findOne({
'Notifications._id' : req.body.NotificationID
}, function(err, doc) {
_.find(doc.Notifications, {_id: req.body.NotificationID}).Status = 1;
doc.save(function (err) {
if (err)
res.send(err);
})
})

Getting undefined when trying to acces a JSON item [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
i am trying to get a JSON and access its objects to retrieve data, all my paths seems to be working good but one specifically is not working. I just checked and the path is the same the other objects i am trying to access, in the console i keep getting undefined as a result. i will appreciate if you guys could tell me whats wrong with the code i will leave you the JSON structure and also the java Scripti hope you guys can help me figuring out, and also would be good if you could give me some tips on my coding because I am learning.
Java Script:
This function is called when you click on some item in a list.
function checkUser(){
console.log("clicked");
var user = $(this).html();
$.getJSON("js/options.json", function(json){
var itemsLength = json.chat.OnlineContacts.length;
for ( var i = 0; i < itemsLength; i++) {
var jsonUserName = json.chat.OnlineContacts[i].name;
var jsonUserStatus = json.chat.OnlineContacts[i].status;
var jsonUserAvatar = json.chat.OnlineContacts[i].avatar;
if(user == jsonUserName){
/*displayChatWindow(jsonUserName, jsonUserStatus, jsonUserAvatar);*/
console.log(jsonUserAvatar);
}
};
});
}
function displayChatWindow(user, status, avatar){
/*var template = _.template($("#windowTemplate").html(), {userName: user, userStatus: status, userAvatar: avatar});
$("body").prepend(template);*/
$(".messages-container").slimScroll({
height: '200',
size: '10px',
position: 'right',
color: '#535a61',
alwaysVisible: false,
distance: '0',
railVisible: true,
railColor: '#222',
railOpacity: 0.3,
wheelStep: 10,
disableFadeOut: false,
start: "bottom"
});
}
And this is the JSON:
{
"chat": {
"NumberOfOnlineContacts": "7",
"NumberOfOfflineContacts": "800",
"OnlineContacts": [
{
"name": "Nandy Torres",
"status": "online",
"avatar": "img/profile-picture2.jpg"
},
{
"name": "Catherine Varela",
"status": "Busy",
"avatar": "img/profile-picture3.jpg"
},
{
"name": "Jhonnatan Gonzalez",
"status": "online",
"avatar": "img/profile-picture4.jpg"
},
{
"name": "Juan Prieto",
"status": "away",
"avatar": "img/profile-picture5.jpg"
},
{
"name": "Alexander Barranco",
"status": "Busy",
"avatar": "img/profile-picture6.jpg"
}
],
"OfflineContacts": [
{
"name": "Nandy Torres"
},
{
"name": "Catherine Varela"
},
{
"name": "Jhonnatan Gonzalez"
},
{
"name": "Juan Prieto"
},
{
"name": "Jhonathan Sanchez"
}
]
}
}
When I try to do the console log on avatar like is in the example I just get undefined, but if i do console.log of name or status y just get the correct values.
Consider restructuring the original JSON object so you can access users directly by their unique id - in this case it appears to be "name".
For example:
{
"chat": {
"NumberOfOnlineContacts": "7",
"NumberOfOfflineContacts": "800",
"OnlineContacts": [
{
"Nandy Torres" : {
"status": "online",
"avatar": "img/profile-picture2.jpg"
}
},
{
"Catherine Varela" : {
"status": "Busy",
"avatar": "img/profile-picture3.jpg"
}
},
{...}
]
}
}
This could be accessed in the following ways without the expense of a loop:
json.chat.OnlineContacts[0].avatar
json.chat.OnlineContacts["Nandy Torres"].avatar
json.chat.OnlineContacts[user].avatar
There's an obvious cost-benefit here, but you may get the best of both by inlcuding the "name" attr as well:
"Nandy Torres" : {
"name": "Nandy Torres",
"status": "online",
"avatar": "img/profile-picture2.jpg"
}
And eventually moving to a more formal unique id:
"123abc" : {
"name": "Nandy Torres",
"status": "online",
"avatar": "img/profile-picture2.jpg"
}
There's lots of excellent ideas for structuring JSON at json.com
Jhonnatan, I'm glad you got your code working. So this isn't really an "answer" to your original question. But you also asked for tips on the coding and how to improve it. That's great that you're looking for ways to improve your code!
Here's one suggestion for you, a simpler way to write the checkUser() function. This is just a direct conversion of your function that should work with the same data format.
function checkUser() {
console.log( "clicked" );
var user = $(this).html();
$.getJSON( "js/options.json", function( json ) {
$.each( json.chat.OnlineContacts, function( i, contact ) {
if( user == contact.name ) {
displayChatWindow( contact.name, contact.status, contact.avatar );
console.log( contact.avatar );
}
});
});
}
Note how the use of the contact object makes it unnecessary to create all those jsonUserXxxx variables, because code like contact.avatar is just as simple and clear as jsonUserAvatar.
I also highly recommend #DaveRomero's excellent answer for a more strategic look at the question of how best to structure your JSON data.
More related reading: this discussion of JSON restructuring that I posted in response to this question earlier today.

Categories