How can I query Firebase for an equalTo boolean parameter? - javascript

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.

Related

How to update field of object in array with Mongoose

I need to find a room by id and update received field to true where user id equals to xx.
The document is here:
{
"_id" : ObjectId("5e5d0d870fc69641a41a3c65"),
"users" : [
ObjectId("5e57d64d92cc878760086980"),
ObjectId("5e57d64592cc87876008697e")
],
"messages" : [
{
"_id" : ObjectId("5e67834b6c8b2d356a4ad9fd"),
"text" : "Hello",
"user" : ObjectId("5e57d64d92cc878760086980"),
"createdAt" : ISODate("2020-03-10T12:08:43.006Z"),
"sent" : true,
"received" : false
},
{
"_id" : ObjectId("5e6783076c8b2d356a4ad9fc"),
"text" : "Hello",
"user" : ObjectId("5e57d64d92cc878760086980"),
"createdAt" : ISODate("2020-03-10T12:07:35.544Z"),
"sent" : true,
"received" : true
}
],
"createdAt" : ISODate("2020-03-02T13:43:35.522Z"),
"updatedAt" : ISODate("2020-03-10T12:08:43.006Z"),
"unReads" : {
"5e57d64d92cc878760086980" : 1,
"5e57d64592cc87876008697e" : 5
},
"__v" : 0
}
****It looks like your post is mostly code; please add some more details.****
You need the positional $ operator:
Model.update({_id: ObjectId("5e5d0d870fc69641a41a3c65"), "messages.user": ObjectId("5e57d64d92cc878760086980")}, { $set: { "messages.$.received": true } })

Mongo db query for finding object type

I've 1000's of users and user data looks like the below.
Some users have the devices as [{some data}] (array), some users have devices as {some data}, and some users have devices as empty [].
I need mongodb query to find the userslist with devices {some data}.
Here is the sample of my users data.
{
"_id" : ObjectId("56fe07bab95708fa18d45ac4"),
"username" : "abcd",
"devices" : []
},
{
"_id" : ObjectId("56fe07bab95708fa18d45df7"),
"username" : "efgh",
"devices" : [
{
"_id" : ObjectId("5827804ef659a60400e12fcb"),
"devicetype" : "web"
}
],
},
{
"_id" : ObjectId("56fe07bab95708fa18d45ae8"),
"username" : "efgh",
"devices" : {
"_id" : ObjectId("5951ea8b47abe300046ea26e"),
"devicetype" : "web"
}
},
{
"_id" : ObjectId("56fe07bab95708fa18d45b5b"),
"username" : "ijkl",
"devices" : [
{
"_id" : ObjectId("59bd2317eeff3200049a2ba6"),
"devicetype" : "ios"
"devicetoken" : "1abffaa4419d498b48d0bf982"
}
],
},
{
"_id" : ObjectId("56fe07bab95708fa18d46102"),
"username" : "efgh",
"devices" : {
"_id" : ObjectId("58c433da28841d00040d3cdb"),
"devicetype" : "web"
}
},
{
"_id" : ObjectId("56fe07bab95708fa18d46177"),
"username" : "efgh",
"devices" : {
"_id" : ObjectId("59d073d96974d20004a4bb9f"),
"devicetype" : "web"
}
},
{
"_id" : ObjectId("56fe07bab95708fa18d456c9"),
"username" : "ijkl",
"devices" : [
{
"_id" : ObjectId("59b93dd2e6673c00044cca49"),
"devicetype" : "ios"
"devicetoken" : "1abffaa4419d498b48d0bf982"
}
],
},
{
"_id" : ObjectId("56fe07bab95708fa18d456f4"),
"username" : "abcd",
"devices" : []
}
You can use $type operator like this
db.collection.find( { "devices" : { $type : "object" } } );
or
db.collection.find({ "devices": { $not: { $type: "array" } }})
Update:
Try one of below query as per your requirement (remove empty objects or keep only empty objects):
db.device.find( {$and:[ {devices:{ $type : "object" }},{devices:{$not: { $type: "array" }}}], devices:{$ne:{}}} );
db.device.find( {$and:[ {devices:{ $type : "object" }},{devices:{$not: { $type: "array" }}}], devices:{$eq:{}}} );
Check this screenshot:
Moreover, please note that you have duplicate keys (_id) in your data set which means those data sets are not inserted into your DB. So query will obviously won't give proper results.
Edit:
OP removed duplicate keys from data set.
You can use $type operator.
Find more detail on this link https://docs.mongodb.com/manual/reference/operator/query/type/

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 to parse this datasnapshot using Firebase and 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());
});
});
});

FS.Collection instance returning undefined when using find()

I'm somewhat new at web development so I apologize if I am using FSCollection incorrectly.
I have a FS.Collection instance that takes in audio files
LectureAudio = new FS.Collection("lectureAudio", {
stores: [new FS.Store.FileSystem("lectureAudio", {
path:"~/digicog/audioUpload",
filter: {
allow: {
contentTypes: ['audio/*'],
extensions: ['mp3', 'wav', 'MP3', 'WAV']
}
}
})]
});
And I am using an input file element to insert audio files into collection.
Template.audioControl.events({
'change #lecAudioPath': function (event) {
var files = document.getElementById("lecAudioPath").files;
if(files.length != 0){
var lecName = Router.current().params._id;
var audioFile = new FS.File(files[0]);
audioFile.metadata = {LectureId: lecName};
LectureAudio.insert(audioFile);
}
}
});
However when I type in LectureAudio.find().fetch() in the console for testing, I get empty brackets [ ].
Even though when I check my mongo database using:
>db.getCollection("cfs.lectureAudio.filerecord").find()
I see that my collection is populated.
{ "_id" : "wwyQtZZNwicbheCch", "copies" : { "lectureAudio" : { "name" : "fWnQyQpEWSXRDeuJq.mp3" } }, "original" : { "name" : "test1.mp3", "updatedAt" : ISODate("2013-08-16T16:07:40Z"), "size" : 8087475, "type" : "audio/mp3" }, "uploadedAt" : ISODate("2015-03-07T06:05:53.589Z") }
{ "_id" : "3rBbFfnGAT3Z8Bkti", "copies" : { "lectureAudio" : { "name" : "Efn235HcCyGrm5TPx.mp3" } }, "original" : { "name" : "test2.mp3", "updatedAt" : ISODate("2013-08-16T16:07:52Z"), "size" : 8806339, "type" : "audio/mp3" }, "uploadedAt" : ISODate("2015-03-07T06:17:06.234Z") }
{ "_id" : "RJ7LLH7XhgG2PnP9g", "copies" : { "lectureAudio" : { "name" : "fWnQyQpEWSXRDeuJq.mp3" } }, "original" : { "name" : "test3.mp3", "updatedAt" : ISODate("2013-08-16T16:07:52Z"), "size" : 8806339, "type" : "audio/mp3" }, "uploadedAt" : ISODate("2015-03-07T06:18:30.454Z") }
{ "_id" : "9YY33kFFbP7oBMjmr", "copies" : { "lectureAudio" : { "name" : "y7KQmq3ReqcP7Pzyw.mp3" } }, "original" : { "name" : "test4.mp3", "updatedAt" : ISODate("2013-08-16T16:07:40Z"), "size" : 8087475, "type" : "audio/mp3" }, "uploadedAt" : ISODate("2015-03-07T20:50:21.226Z") }
How do I get the collection to show?
You probably forgot to publish and subscribe to the collection.
On the server:
Meteor.publish('lecture_audio', function () {
return LectureAudio.find();
}
And on client:
Meteor.subscribe('lecture_audio');
More info in the docs here

Categories

Resources