How to store HourTime parameter with mongoose schema? - node.js

I want to store Documents with HourTime parameter.
The requirement is to be store HourTime of opening hour of supermarket and I need the option to query "Which supermarket is open now"?
what the best practice to do that and how to develop it?
I use nodejs, express and mongoose.
thanks

You can use hour and minute. First you need to create the fields, if you have multiple times depending on week day you can also use an array.
{
_id: ObjectId("600631c7c8eb4369cf6ad9c8"),
name: "Market X",
openHour: 10, // number between 0 and 23
openMinute: 30 // number between 0 and 59,
closeHour: 18, // number between 0 and 23,
closeMinute: 30, // number between 0 and 59
weekDay: 1 // number beetween 1 and 7
}
With a model like this you can do a find:
{
weekDay: 1, // number between 1 (Monday) and 7 (Sunday)
openHour: { $lte: 11 }, // number between 0 and 23
openMinute: { $lte: 32 }, // number between 0 and 59
closeHour: { $gte: 17 }, // number between 0 and 23
closeMinute: { $gte: 20 } // number between 0 and 59
}
The params for the query in find you can achieve using time with day.js, for example dayjs().format("HH") will retrieve the actual hour where your node is running.

Related

node.js write data to influxdb timestamp is wrong

I'm writing data to my influxdb with node.js,but the time always wrong like,
I'm using Datetime in 'luxon'.
const from = DateTime.fromObject({ year: 2021, month: 12, day: 1, hour: 8});
const to = from.plus({ day: 1 });
let anchor = from;
whiel(anchor < to) {
notification.time = anchor.valueOf();
await write(notification);
anchor = anchor.plus({ minute: 5 });
}
the point should start from 2021/12/1 08:00:00 to 2021/12/3 15:55:00.
every 5 mins have a point,but see the picture in my influxdb
it seems like every 11 mins and 50 secs have one point, I don't understand.

MongoDB - How to get the documents based on two column values

My MongoDB collection with sample data is attached with the screenshot below
I want to fetch rows by passing grade value and the resulting records should be returned as follows
case 1: when grade = 12, Row 1,3,6 and 7 should be returned ie given
grade 12 should compare with gradeFrom and gradeTo
case 2: when grade = 1, Row 5 should returned
As a summary of above cases, the given grade should be greater than or equal to gradeFrom AND less than or equal to gradeTo.
The mongoose query that I used is given below, but the data returned is empty in my code
let andCondition = [];
let grade = 12;
andCondition.push({ gradeFrom: {$gte: grade}});
andCondition.push({ gradeTo: {$lte: grade}});
let data = await Course.find({$and :andCondition});
console.log(andCondition) gives the below object
[
{ gradeFrom: { '$gte': 12 } },
{ gradeTo: { '$lte': 12 } }
]
Please help me to get this done.
You have reversed the range logic.
In Math, it should be:
gradeFrom <= grade <= gradeTo
While in MongoDB query:
{ gradeFrom: { $lte: grade } }
{ gradeTo: { $gte: grade } }

NodeJS MongoDB Count entries with same value in field

I have the following collection
_id: someid
name: Name 1
status: 0
ref: 152
_id: someid
name: Name 1
status: 0
ref: 152
_id: someid
name: Name 1
status: 3
ref: 152
_id: someid
name: Name 1
status: 0
ref: 273
_id: someid
name: Name 1
status: 3
ref: 679
I'd like to get a result that tells me how many times "ref" appears with the same value where the entry has the status anything except 3. So for example the result I'm looking for is basically
{"152": 2, "273": 1, "679": 0}
Since "ref: 152" appears 2 times while the status is not 3 and "ref: 273" appears 1 times while the status is not 3. I'm using NodeJS, Express, and MongoDB. I've tried to aggregate which to an extent does work however since 679 has 0 the aggregation result omits "679: 0" and that causes the React template to throw an error declaring it undefined. Using aggregation also formats it differently so occasionally the wrong amount is displayed on different rows. I feel if I can access the count by using the reference number as the key it'd be accurate but I can't figure out how to achieve this.
EDIT: I have solved my issue like this:
const count = {}
docs.map((doc) => {
count[doc.ref] = 0
})
docs.map((doc) => {
doc.status < 3 && count[doc.ref]++
})
Which returns exactly what I specified I needed above however I was wondering if there was an even cleaner way to do it?
You can use Array.reduce() function as well.
const countRef = docs.reduce((count, doc) => {
count[doc.ref] = (doc.status !== 3) ? (count[doc.ref] || 0) + 1 : (count[doc.ref] || 0);
return count;
}, {});
// countRef - {"152": 2, "273": 1, "679": 0}

How to fetch data using between with two columns in sequelize

Please help me to write sequelize function for below MYSQL query
select * from userCategory where 25 between minAge and maxAge;
A Table looks like below
userRecords
id minAge maxAge category
1 11 20 category 1
2 21 30 category 2
Thanks in advance
You cannot simply use BETWEEN as it requires a column name or a computed table (like WITH) for the left side of the SQL function
The simplest solution would be:
models.userCategory.findAll({
where: {
minAge: { [Op.lt]: 25 },
maxAge: { [Op.gt]: 25 },
},
})
If you must use BETWEEN then sequelize will make your life much harder, as you will require to use sequelize.literal('SELECT 25 as age') to start with in order to have a pseudo table ... just so you can use BETWEEN?

MongoDB average on dynamic keys

I'm not sure if this is possible in pure mongo. I have looked at Mongo Aggregate and Map Reduce.
I have the following collection:
{
id: 1
activity: "running"
result: {
distance: 10
duration: 20
}
},
{
id: 2
activity: "running"
result: {
distance: 30
duration: 40
}
},
{
id: 3
activity: "weightlifting"
result: {
reps: 10
weight: 30
}
}
Now I would like to get the average of any field within the result part of the item in the collection of a certain type.
For example: I fetch all the running activities and want the average of distance and duration. However I want to query that dynamically. Without explicitly stating distance and duration. The only thing I know is: "The fields I want are within the results part of the object."
The output would be something like:
{
activity: "running"
result: {
distance: 20
duration: 30
}
}
Currently I have a solution that fetches all activities of a certain type into Node, and use Javascript to determine the average dynamically. Though I'm curious to see if I can do this in Mongo directly.

Resources