I have my object as follows
-Notifications
userId
key1
datakey1
date: 10-10-2016
time: 3:20 pm
status: open
key2
datakey2
date: 11-10-2016
time: 5:00 pm
status: close
I'm having ref path till Notifications/userId
How do I retrieve data where status='open'
Code from comments:
ref.orderByChild("status")
.equalTo('open')
.on("value", function(snapshot) { console.log(snapshot.key); });
Firebase queries can only contain one dynamic key.
In your case you have two dynamic keys under that key1/key2 and datakey1/datakey2. You'll either have to put one of those at a fixed location (e.g. key1/my/status, key2/my/status) or you will have to structure your data differently.
notificationsStatusPerUser
userId: {
key1_datakey1: {
status: "open",
path: "key1/datakey1"
}
key2_datakey2: {
status: "close",
path: "key2/datakey2"
}
}
}
Now you can find all open items for a specific user with:
var query = ref.child('notificationsStatusPerUser')
.child(uid)
.orderByChild(status)
.equalTo('open');
query.on('child_added', function(snapshot) {
ref.child('notifications')
.child(uid)
.child(snapshot.val().path)
.once('value', function(linkedSnapshot) {
console.log(linkedSnapshot.val());
});
};
Related
Unable to query using date while passing through mongo data api. I would like to query the database to find fetch all entries at the time
The below code returns empty document
The sample db :
[{
sensorId:'1231541',
sensorTimestamp:'2022-01-28T20:14:26.223+00:00'
}]
await superagent.post(`${url}/action/${body.action}`)
.send({
dataSource: 'Cluster0',
database:'testDB',
collection: body.collection,
filter: body.filter,
sort: body.sort,
});
const config = {
action: 'find',
collection: 'testCollection',
filter: {
sensorId: '1231541',
sensorTimestamp: {
$gte: new Date('2022-01-28T20:14:26.223+00:00'),
$lt: new Date('2022-01-28T20:33:16.324+00:00'),
},
},
sort: {
name: 1,
},
};
You must query dates in millis, not tje string representation of that.
I have a Firestore collection set up as thus:
EDIT: As requested, here's a screenshot showing the second document which contains the same PostId and 'poster' as the single document being retrieved.
Now in this chats2 collection there are two documents with the same 'postId' and 'poster'. I am using the following query. Can anyone please show me why it is returning only one message?
async function getIndividualMessage() {
try{
return await useFireStore
.collection('chats2')
.where("postId", "==", `${postId}`)
.where("poster", "==", `${posterId}`)
.orderBy('createdAt', 'asc')
.onSnapshot(snapshot => {
let eachMessage = [];
snapshot.forEach(doc => {
eachMessage.push({...doc.data(), id: doc.id })
});
setTheMessageData(eachMessage);
});
}
catch{
console.log('error on getIndividualMessage')
}
finally{
}
}
As far as I'm aware in the query I'm asking for all the entries where the postID = $postId and the poster = $posterId.
The value of console.log("the messagedata is :",theMessageData[0]) is:
the messagedata is :
{createdAt: t, postId: "PsulTQciDB4iBfPQRUbn", poster: "VeFpTQuWlLc859TR8O3h9F10ky53",
message: "Admin on Amazon 1", id: "QWHgZ6Z9JsmYLSiACUjT"}
createdAt: t {seconds: 1611056590, nanoseconds: 431000000}
id: "QWHgZ6Z9JsmYLSiACUjT"
message: "Admin on Amazon 1"
postId: "PsulTQciDB4iBfPQRUbn"
poster: "VeFpTQuWlLc859TR8O3h9F10ky53"
EDIT TWO: The result of console.log("the messagedata is :",theMessageData) is (hence the [0] in the first console log:
[{…}]
0:
createdAt: t {seconds: 1611056548, nanoseconds: 503000000}
id: "uu9QbeZncCBVdlPVDGe6"
message: "matt on Amazon 1"
postId: "PsulTQciDB4iBfPQRUbn"
poster: "WD3YintPmjhztE7horU8VpfOnoo1"
There should be two messages are there are two entries with those PostId and Poster values at the bottom. I've been on this for about the last four hours and I still can't figure it out. Is there something obviously wrong that I doing?
Any help very much appreciated.
Kind regards,
Matt
I am new to MongoDB and I've been trying to get scheduled control messages in my collection , for example one CM is scheduled for today 15h and now is 15h, by logic i should compare the date using $lte (less than or equal)
the query:
/*Getting the Date (my schedule is only with hours and minutes)*/
var nowDate = new Date();
nowDate.setSeconds(0);
nowDate.setMilliseconds(0);
/*The Query*/
dbo.collection("control_message").find(
{ "status": { $in: [3,4] }},
{
$or: [ { schedule:{$exists: false}},{schedule:{date:{ $lte :nowDate}}}]
}
)
why i am asking this?
because there are CMs (control messages) scheduled for 17h even though now it's 15h and the query is getting them.
I printed the nowDate to verify: 2020-12-13T15:33:00.000Z
The scheduled time is: 2020-12-13T17:00:00.000Z
same query on MySQL (works):
SELECT id_control_message AS control_message_id , app_id, title, body, channel,url_push, img_push, silent, status
FROM control_message
WHERE (status = 3 OR status = 4)
AND (schedule IS NULL OR schedule <= NOW())
Control Message Document example:
{
_id: '5fd3e48eac3f2b3ede0a6a52',
sent_in: {
date: 2020-12-11T21:28:46.760Z,
short_date: 2020-12-11T21:28:46.760Z
},
sender_id: 266,
app_id: 190,
message_type_id: 1,
title: '',
body: '',
schedule: {
date: 2020-12-13T17:00:00.000Z,
short_date: 2020-12-13T17:00:00.000Z
},
ip: '172.31.55.83',
status: 4
}
Thanks to turivishal, I've noticed in the playground example he sent me that the logic of the my query was wrong since i didn't add the $and operator,it wasn't returning the right results.
Not only that , but specifying which date to compare with "schedule.date" instead of using just "schedule" was the correct way to compare (in my case)
The corrected query:
dbo.collection("control_message").find({
$and: [
{"status": { $in: [3,4] }},
{
$or: [ { schedule:{$exists: false}},{"schedule.date":{ $lte :nowDate}}]
}
]
})
I have a ReactApp with a MongoDB based on local events here in my city. The current schema looks like this.
const eventSchema = mongoose.Schema({
start: String,
end: String,
name: String,
loc: { // Reference: https://mongoosejs.com/docs/geojson.html
type: {
type: String,
enum: ['Point']
},
coordinates: {
type: [Number]
}
},
web: String,
desc: String
});
I have an event button where I press, it gets the data from the DB and renders it to the HTML Page
callbackGetData() {
fetch('/api')
.then(resp => {
console.log(resp);
return resp.json();
})
.then(jdat => {
console.log(jdat);
this.setState({ data: JSON.stringify(jdat)}); // Print to debug area.
// todo: Update marker on the map?
});
}
when printed on the screen, this the results from the JSON objects that are stored in the database
[{"loc":{"coordinates":[-122.698687,45.526974],"type":"Point"},"_id":"5e5c3cde56138449ec49905f","start":".","end":".","name":"Portland Dining Month","web":".","desc":".","__v":0},
{"loc":{"coordinates":[-122.680712,45.509871],"type":"Point"},"_id":"5e5c3cde56138449ec499060","start":".","end":".","name":"Test event #PSU","web":".","desc":".","__v":0},
{"loc":{"coordinates":[-122.674043,45.481716],"type":"Point"},"_id":"5e5c3cde56138449ec499057","start":".","end":".","name":"Transgender Clients: Assessment and Planning for Gender-affirming Medical Procedures","web":".","desc":".","__v":0}]
If I try to go and print it with
console.log(jdat);
this.setState({ data: JSON.stringify(jdat.name)});
It says that it undefined. How can I go about printing out just the individual names and location coordinates and storing them in a variable I can use elsewhere in the file? Thanks
Looks like you have a array of data coming from database. so trying jdat.name will not work. You need to iterate over the array.
try the following code.Hope you are looking for the same
var jdat = [{"loc":{"coordinates":[-122.698687,45.526974],"type":"Point"},"_id":"5e5c3cde56138449ec49905f","start":".","end":".","name":"Portland Dining Month","web":".","desc":".","__v":0},
{"loc":{"coordinates":[-122.680712,45.509871],"type":"Point"},"_id":"5e5c3cde56138449ec499060","start":".","end":".","name":"Test event #PSU","web":".","desc":".","__v":0},
{"loc":{"coordinates":[-122.674043,45.481716],"type":"Point"},"_id":"5e5c3cde56138449ec499057","start":".","end":".","name":"Transgender Clients: Assessment and Planning for Gender-affirming Medical Procedures","web":".","desc":".","__v":0}]
jdat.forEach(item =>{
console.log("Name : ",item.name)
console.log("Location Coordinates : ",item.loc.coordinates)
})
I'm trying make CRUD operation in Electron, where using MongoDB, and Mongoose for Electron connect to database.
I have a function list for return the "return" of Mongoose. When I debugging return data, is show correct in my terminal
ipc.on('products.list', function(event, query) {
Service.list(query, function(err, data) {
console.log(data); // this will be print correct result
event.sender.send('product.list', data);
});
});
Result of code upper part:
[ { _id: 55c15f2981260a6f0ef8a657,
__v: 0,
deleted_at: '',
updated_at: '',
created_at: Tue Aug 04 2015 21:51:52 GMT-0300 (BRT),
measure: '',
aplication: '',
model: 'Mode XBA',
reference: 'Reference test 123',
code: '2028' } ]
But when I debug return data by client side with fallowing code, result is not correct and is not equal server side print.
Client side code:
ipc.on('product.list', function(data) {
window.data = data;
console.log(data); // this will print incorrect result
});
ipc.send('products.list', {});
Result of client side received:
{
"$__":{....},
"_doc":{...},
"_posts":{...},
"_pres":{...},
"isNew":false
}
Contains more objects in each element.
Why this happens? How to can I resolve this problem?
I resolved this problem!
This return is result from Mongoose
{
"$__":{....},
"_doc":{...},
"_posts":{...},
"_pres":{...},
"isNew":false
}
For return only property, is need add options {lean : true}
Ex:
Model.find(this.query)
.lean()
.exec(function(err, data) {}
);
More detail in Mongoose Doc