How to parse this datasnapshot using Firebase and JavaScript? - javascript

I have this data structure
{
"job-requests" : {
"pending" : {
"-KkyZGfqmiIVryyLAZpD" : {
"job_details" : "asd",
"job_type" : "Repair Required",
"location" : "123",
"location_lat" : 14.164633210106128,
"location_lng" : 121.24110514763743,
"timestamp" : 1495698316411
}
}
},
"office-info" : {
"123" : {
"office_acronym" : "123",
"office_contact_number" : "123-1234",
"office_current_head" : "None",
"office_name" : "123",
"office_parent_unit" : "123"
}
},
"office-location-list" : {
"123" : {
"location_lat" : 14.164633210106128,
"location_lng" : 121.24110514763743
}
},
"users" : {
"MBR5o37xafUyuLw14Xqa1ku0Zui1" : {
"designation" : "staff",
"email" : "123#asd.com",
"given_name" : "23",
"last_name" : "123",
"password" : "1234567",
"timestamp" : 1495617328793
},
"Nwacy3ADczgLC85OvSAgUNEGMkx2" : {
"designation" : "staff",
"email" : "adsasd#asdas.com",
"given_name" : "122123",
"last_name" : "12",
"password" : "asdasdsadasd",
"timestamp" : 1495681430048
}
}
}
I will be needing the keys [pending, active, finished] along with the data of the newly added child. This is how I accessed Firebase
firebase.database ().ref ('job-requests').on ('child_added', (snapshot) => {
console.log (snapshot.key); // prints out [pending, active, finished]
console.log (snapshot.val()); // prints out an object
});
It prints this on the console:
I tried using JSON.parse (), snapshot.child (path), snapshot.field, and snapshot[field] but errors are thrown out. How do I do this?

Your code gets all job requests. Since those are in a hierarchy by their state, your code will need to handle this:
firebase.database ().ref ('job-requests').on ('child_added', (snapshot) => {
snapshot.forEach((stateSnapshot) => {
console.log(stateSnapshot.key); // 'pending', etc
stateSnapshot.forEach((jobSnapshot) => {
console.log(jobSnapshot.key);
console.log(jobSnapshot.val());
});
});
});

Related

getBypage in Nested Array in MongoDB using Aggregate

I am using mongoDB as backend server, I have nested array(one level array) like this
{
"_id" : ObjectId("60b1fc6d3c43f74e0c1dba92"),
"seriesId" : "60acebf73acb5b3a98d14331",
"name" : "Season 1",
"logoURL" : "uploads/season/1622277216401.png",
"yearOfPublish" : "2021-05-29",
"description" : "Season 1",
"createdBy" : ObjectId("609cbf49ba46cc3924859ab5"),
"createdOn" : "2021-05-29T08:33:49.480Z",
"episode" : [
{
"seasonId" : "60b1fc6d3c43f74e0c1dba92",
"name" : "Episode 1",
"id" : 0,
"logoURL" : "uploads/episode/1622278616899.png",
"dateOfTelecast" : null,
"description" : "sadfgh",
"duration" : "30",
"videoType" : "customURL",
"embedCode" : "",
"url" : "https://youtu.be/kbpsXMUr7ss",
"liveboxChannel" : "",
"createdOn" : "2021-05-29T08:56:59.230Z",
"createdBy" : ObjectId("609cbf49ba46cc3924859ab5"),
"_id" : "ZaVrpOLO5"
},
{
"seasonId" : "60b1fc6d3c43f74e0c1dba92",
"name" : "Episode 2",
"id" : 0,
"logoURL" : "uploads/episode/1622279206607.png",
"dateOfTelecast" : null,
"description" : "adfd",
"duration" : "30",
"videoType" : "customURL",
"embedCode" : "",
"url" : "https://youtu.be/kbpsXMUr7ss",
"liveboxChannel" : "",
"createdOn" : "2021-05-29T09:06:48.637Z",
"createdBy" : ObjectId("609cbf49ba46cc3924859ab5"),
"_id" : "9GKqXhxcH"
},}
I have more no of seasons. from the season collection,i have episode array under the name of Episode.
Now My frontend page required that episode array alone.
response = {episode: all the episode data} and this episode data is based on skip and limit value
I have tried something in mongodb,
db.getCollection('season_copy').aggregate([
{$project: {
episodes: {
$cond:{ if: { $isArray: "$episode" }, then: { input:"$episode" }, else: 0 }
},
},
},
])
Can anyone suggest me some idea?
Check this out:
Without aggregate:
db.getCollection('season_copy')
.find({ _id: ObjectID(id)})
.project({ episode: 1 }).toArray();
With aggregate:
MongoDB playground
db.getCollection('season_copy')
.aggregate([
{
$match: {
_id: ObjectId("60b1fc6d3c43f74e0c1dba92")
}
},
{
$project: {
episode: 1
}
}
])

How to remove document in two different collection using same id at same time in mongodb on feathers application

I'm trying to remove document in two different collection using same id at same time. Is there any possibilities?
user collection:
{
"_id" : ObjectId("5a310315f685dd5038fecaaa"),
"userId" : 3,
"accountId" : 1,
"userType" : "DRIVER",
"firstName" : "Karthi",
"lastName" : "keyan",
"email" : "karthikeyan.a1#gmail.com",
"password" : "$2a$12$KFYc6riMnqTuzXhR0ssKZQmejAU4RF8FthAIQD4sgOUcALesp7DaJxK",
"phone" : "xyz",
"updatedAt" : ISODate("2017-12-13T10:38:13.492Z"),
"createdAt" : ISODate("2017-12-13T10:38:13.492Z"),
"__v" : 0
}
worker collection:
{
"_id" : ObjectId("5a310315f685dd5038fecaab"),
"workerId" : 1,
"accountId" : 1,
"name" : "Karthikeyan",
"email" : "karthikeyan.a1#gmail.com",
"mobile" : "xyz",
"type" : "DRIVER",
"joinDate" : ISODate("2017-12-13T10:38:13.070Z"),
"assignedVehicleId" : "23423231",
"licenseNumber" : "TN2506",
"createdBy" : "1",
"createdDate" : ISODate("2017-12-13T10:38:13.070Z"),
"updatedBy" : "1",
"updatedDate" : ISODate("2017-12-13T10:38:13.070Z"),
"regularHours" : 3600,
"regularRates" : 1500,
"overtimeRates" : 400,
"distanceRate" : 1000,
"stopRate" : 50,
"workerStatus" : "AVAILABLE",
"userId" : 3,
"__v" : 0
}
now i want to remove these two document at same time using userId.
Database adapters allow to call remove with null and a query that will remove all entries matching that query (see the documentation). In your case:
app.service('users').remove(null, { query: { userId: 3 } });
app.service('workers').remove(null, { query: { userId: 3 } });
Removing related entries (e.g. remove all workers for that user once the user has been removed) can be done in an after hook:
app.service('users').hooks({
after: {
async remove(context) {
const user = context.result;
await context.app.service('workers').remove(null, {
query: { userId: user.userId }
});
}
}
});

How can I query Firebase for an equalTo boolean parameter?

My database looks like
{
"chats" : {
"-K5hUtxNOPLWwRTb8fAj" : {
"clientId" : 893,
"messages" : {
"-K5hUtyCwWuPeFT0cSXr" : {
"chatKey" : "-K5hUtxNOPLWwRTb8fAj",
"messageText" : "new message",
"timestamp" : 1450314801055,
"userId" : "19eaa3f0-4ab3-44b4-b418-03b64ca2313a"
},
"-K5hUvwKsAOvuvt-ymFG" : {
"chatKey" : "-K5hUtxNOPLWwRTb8fAj",
"messageText" : "did this work",
"timestamp" : 1450314809127,
"userId" : "48f7a208-5647-4d0e-921c-c49595de1db2"
}
},
"newQuestion" : false,
"startedByUserId" : "19eaa3f0-4ab3-44b4-b418-03b64ca2313a"
},
"-K5hVKjs4SkSHD7WTh1I" : {
"clientId" : 518,
"messages" : {
"-K5hVNzPKNgxLCgkfInI" : {
"chatKey" : "-K5hVKjs4SkSHD7WTh1I",
"messageText" : "this is new",
"timestamp" : 1450314928109,
"userId" : "19eaa3f0-4ab3-44b4-b418-03b64ca2313a"
}
},
"newQuestion" : true,
"startedByUserId" : "19eaa3f0-4ab3-44b4-b418-03b64ca2313a"
}
}
}
How can I get all chats that have a newQuestion set to true? I've tried a few different queries, the latest is:
firebaseDb.child("chats/newQuestion").equalTo(true).once("value"...
But that complains about an order being needed for a boolean?
You have to specify an orderBy method first.
var query = firebaseDb.child("chats").orderByChild("newQuestion").equalTo(true);
Here's the Firebase docs on querying.

Mongodb update operation inside sub array

I am extremely new to mongodb and am facing a little trouble with an update operation. Here is the document:
{
"username" : "amitverma",
"notifications" : {
"notification_add_friend" : [
{
"sender" : "macbook",
"action" : "",
"type" : "",
"objectType" : "request",
"objectUrl" : "",
"isUnread" : true
},
{
"sender" : "safari",
"action" : "",
"type" : "",
"objectType" : "request",
"objectUrl" : "",
"isUnread" : true
},
{
"sender" : "chrome",
"action" : "",
"type" : "",
"objectType" : "request",
"objectUrl" : "",
"isUnread" : true
}
]
},
"_id" : ObjectId("526598c86f45240000000001")
}
{
"username" : "macbook",
"notifications" : {
"notification_add_friend" : [
{
"sender" : "amitverma",
"action" : "",
"type" : "",
"objectType" : "a_r",
"objectUrl" : "",
"isUnread" : true
}
]
},
"_id" : ObjectId("526598d06f45240000000002")
}
I want to remove the sub array with {"sender":"safari"} within "username":"amitverma"
I have tried $elemMatch with $set, but just couldn't get the query correctly.
You don't want to use $set here, but $pull (see docs), and while you could use $elemMatch to further specify your query, you do not need to.
The following would pull all add friend notifications with {"sender": "safari"} from the sub array of documents matching {"username": "amitverma"}
db.yourcollection.update({"username": "amitverma"}, {
$pull: {"notifications.notifications_add_friend": {"sender": "safari"}}
})
As to your comment, if you wanted to update a particular element you would use $set in combination with $elemMatch and the positional operator $. For your example, something like:
db.yourcollection.update({
"username": "amitverma",
"notifications.notifications_add_friend": {
$elemMatch: {"sender": "safari"}
}
}, {
$set: {
"notifications.notifications_add_friend.$.isUnread": false
}
})

Map Reduce for MongoDB

I have a collection in which each object contains details of the user along with the comments user has given on specific products which is given below
{
"_id" : ObjectId("51efcbc8786df13540e46887"),
"value": {
"UserDetails" : [
[
{
"country" : "CA",
"gender" : "M",
"age" : "18",
"userIdtemp" : ObjectId("51efcbc8786df13540e46887")
}
]
],
"comments" : [
{
"commentId" : ObjectId("51efcc41786df13540e46891"),
"comment" : "Hey, what's up?",
"created" : ISODate("2013-07-24T12:44:49.400Z"),
"productId" : ObjectId("51efcbd4786df13540e4688c"),
"userId" : ObjectId("51efcbc8786df13540e46887")
},
{
"commentId" : ObjectId("51efcc43786df13540e46893"),
"comment" : "Cool",
"created" : ISODate("2013-07-24T12:44:51.004Z"),
"productId" : ObjectId("51efcbd2786df13540e4688b"),
"userId" : ObjectId("51efcbc8786df13540e46887")
}
]
}
}
{
"_id" : ObjectId("51efcbc8786df13540e46888"),
"value" : {
"UserDetails" : [
[
{
"country" : "US",
"gender" : "M",
"age" : "25",
"userIdtemp" : ObjectId("51efcbc8786df13540e46888")
}
]
],
"comments" : [
{
"commentId" : ObjectId("51efcc41786df13540e46892"),
"comment" : "Not much",
"created" : ISODate("2013-07-24T12:44:49.475Z"),
"productId" : ObjectId("51efcbd4786df13540e4688c"),
"userId" : ObjectId("51efcbc8786df13540e46888")
}
]
}
}
{
"_id" : ObjectId("51efcbc8786df13540e46889"),
"value" : {
"UserDetails" : [
{
"country" : "US",
"gender" : "F",
"age" : "13",
"userIdtemp" : ObjectId("51efcbc8786df13540e46889")
}
]
}
}
I have to extract comments separately along with there userDetails with key as productId so i have written map something like following
mapCommentsFrom = function(){
if("comments" in this.value)
{
for(var idx = 0;idx<this.value.comments.length;idx++){
var key = this.value.comments[idx].productId;
var value = [{
commentId: this.value.comments[idx].commentId,
comment:this.value.comments[idx].comment,
created:this.value.comments[idx].created,
productId:this.value.comments[idx].productId,
userId:this.value.comments[idx].userId,
country:this.value.UserDetails[0][0].country,
gender:this.value.UserDetails[0][0].gender,
age : this.value.UserDetails[0][0].age
}]
}
}
emit(key,value);
}
reduceFrom = function(k,values){
return values;
}
but where ever the number of comments are more than one i am getting only the last comment along with user details and other's key as well as value is coming null. Something like this
{ "_id" : null, "value" : null }
{
"_id" : ObjectId("51efcbd2786df13540e4688b"),
"value" : [
{
"length" : 2,
"commentId" : ObjectId("51efcc43786df13540e46893"),
"comment" : "Cool",
"created" : ISODate("2013-07-24T12:44:51.004Z"),
"productId" : ObjectId("51efcbd2786df13540e4688b"),
"userId" : ObjectId("51efcbc8786df13540e46887"),
"country" : "CA",
"gender" : "M",
"age" : "18"
}
]
}
{
"_id" : ObjectId("51efcbd4786df13540e4688c"),
"value" : [
{
"length" : 1,
"commentId" : ObjectId("51efcc41786df13540e46892"),
"comment" : "Not much",
"created" : ISODate("2013-07-24T12:44:49.475Z"),
"productId" : ObjectId("51efcbd4786df13540e4688c"),
"userId" : ObjectId("51efcbc8786df13540e46888"),
"country" : "US",
"gender" : "M",
"age" : "25"
}
]
}
Can somebody please help me as to what i am missing?
Thanks for help in advance
I cannot add comments due to reputation. But had you considered using the aggregation framework.
The $unwind operator will return you an array of sub documents quite easily and it's faster than using map/reduce.
I'm not sure it will exactly do what you're looking for but may help.
Take a look, http://docs.mongodb.org/manual/reference/aggregation/unwind/
Its because you are not emitting them in the map function.
Move the emit function inside the for loop.
mapCommentsFrom = function(){
if("comments" in this.value){
for(var idx = 0;idx<this.value.comments.length;idx++){
var key = this.value.comments[idx].productId;
var value = {
commentId: this.value.comments[idx].commentId,
comment:this.value.comments[idx].comment,
created:this.value.comments[idx].created,
productId:this.value.comments[idx].productId,
userId:this.value.comments[idx].userId,
country:this.value.UserDetails[0][0].country,
gender:this.value.UserDetails[0][0].gender,
age : this.value.UserDetails[0][0].age
}
emit(key,value);
}
}
}
Then you may also need to rewrite your reduce function to something like this
reduceFrom = function(k,valueArray){
var returnData = { values : [] } ;
for(var i=0;i<valueArray.length;i++)
returnData.values.push(valueArray[i]);
return returnData;
}
By far the easiest is to just use the aggregation framework for this. The aggregation framework allows you to execute operators on data, there is $match for doing queries (like find()) and various others. See for more information: http://docs.mongodb.org/manual/core/aggregation/
The aggregation framework also has an $unwind function that does exactly what you want. You use it like:
db.collection.aggregate( [
{ $unwind: '$value.comments' },
{ $project: {
_id: '$value.comments.productId',
value: 1
} }
] );
On your sample documents, this returns:
{
"result" : [
{
"_id" : ObjectId("51efcbd4786df13540e4688c"),
"value" : {
"UserDetails" : [
[
{
"country" : "CA",
"gender" : "M",
"age" : "18",
"userIdtemp" : ObjectId("51efcbc8786df13540e46887")
}
]
],
"comments" : {
"commentId" : ObjectId("51efcc41786df13540e46891"),
"comment" : "Hey, what's up?",
"created" : ISODate("2013-07-24T12:44:49.400Z"),
"productId" : ObjectId("51efcbd4786df13540e4688c"),
"userId" : ObjectId("51efcbc8786df13540e46887")
}
}
},
{
"_id" : ObjectId("51efcbd2786df13540e4688b"),
"value" : {
"UserDetails" : [
[
{
"country" : "CA",
"gender" : "M",
"age" : "18",
"userIdtemp" : ObjectId("51efcbc8786df13540e46887")
}
]
],
"comments" : {
"commentId" : ObjectId("51efcc43786df13540e46893"),
"comment" : "Cool",
"created" : ISODate("2013-07-24T12:44:51.004Z"),
"productId" : ObjectId("51efcbd2786df13540e4688b"),
"userId" : ObjectId("51efcbc8786df13540e46887")
}
}
},
{
"_id" : ObjectId("51efcbd4786df13540e4688c"),
"value" : {
"UserDetails" : [
[
{
"country" : "US",
"gender" : "M",
"age" : "25",
"userIdtemp" : ObjectId("51efcbc8786df13540e46888")
}
]
],
"comments" : {
"commentId" : ObjectId("51efcc41786df13540e46892"),
"comment" : "Not much",
"created" : ISODate("2013-07-24T12:44:49.475Z"),
"productId" : ObjectId("51efcbd4786df13540e4688c"),
"userId" : ObjectId("51efcbc8786df13540e46888")
}
}
}
],
"ok" : 1
}

Categories

Resources