Cannot get collections by date with mongoose - javascript

I can not query the collection filtering by a date
The following code is that I have so far
//The following code shows how my schema is:
date: {type: Date, required: true}
//This is a date from a collection in MongoDB:
date: 2019-09-06T16:48:14.000+00:00
//This is how I saved the date in the MongoDB:
"2019/09/09 08:55:15"
//And this is how I perform the query in NodeJS:
let year = req.query.year;
let month = req.query.month;
let day = req.query.day;
let startDate = new Date(year, month, day);
let endDate = new Date(year, month, day);
// find documents in MongoDB
let query = SALES.find({ date: { $gte: startDate, $lte: endDate }});
// execute the query at a later time
query.exec(function (err, item) { // item is a dictionary
if (err) return handleError(err); // throws an error if any
if (item === null || item.length === 0) {
res.json({
status: 'empty',
});
}
else {
res.json({
salesRecord: item
});
}
});
I read that is easy to get, but I am not able to do it. Any help is welcome 🙏
I have not error on the query, simply I get the response as empty.
The expected results is to get the dates from the specified date

Short answer
Date you saved("2019/09/09 08:55:15") is being treated as a string.
Try this:
db.mycollection.find({
"date" : {"$gte": new Date()}
})
or
db.mycollection.find({
"date" : {"$gte": ISODate(new Date())} // current date
});
Description
Mongodb shell provides various methods to return the date.It can be a string or as a Date object:
Date() method which returns the current date as a string.
new Date() constructor which returns a Date object using the ISODate() wrapper.
ISODate() constructor which returns a Date object using the ISODate() wrapper.

Related

MongoDB/Mongoose - Find all where a specific Date is in a Date Range

for example I have documents with this field:
startDate: 2021-04-14T22:00:00.000+00:00
endDate: 2021-04-19T22:00:00.000+00:00
and I want to get all documents where a specific date (like today) is in the date range.
Is it possible to make such a query?
For example if I search for 18th April, then I get that document.
I thought something like this:
db.posts.find(
{
$gte: { startDate: new Date() },
$lt: { endDate: new Date() }
});
But this doesn't work... I get an error The provided parameters were invalid. Check your query and try again.
I think new Date() is not correct in Node.js?
EDIT:
This is my Controller:
const getActiveTours = async (req, res) => {
try {
const activeTours = await Tour.find({
startDate: { $gte: new Date() },
endDate: { $lt: new Date() },
}).exec();
res.status(200).send(activeTours);
} catch (error) {
return res.status(500).send({ errorMessage: error });
}
};
I exported it and here is my endpoint:
router.get('/getactivetours', tourController.getActiveTours);
I tried to call this in Postman but get an empty [] back...
Your syntax is wrong, try this one:
db.posts.find(
{
startDate: {$gte : new Date() },
endDate: {$lt : new Date() }
});

Query by date range using Mongoose for dates that have format MM/DD/YY h:m and type String

I have a schema like this
const someSchema = new mongoose.Schema (
{
updatedAt: { type: string }
}, { timestamps: { currentTime: () => moment().format("MM/DD/YY, h:mm") } }
);
I want to query this collection to find the documents updated within a date range for example:
12/05/20 to 12/31/20, hours and minutes don't matter. My startDate and endDate is in the YYYY-MM-DD format. I have tried to find
updatedAt: {
$gte: new Date(startDate),
$lte: new Date(endDate)
}
or
updatedAt: {
$gte: startDate,
$lte: endDate
}
but they are not working. Thank you for your time!
First try to alter moment().format("MM/DD/YY, h:mm")
to moment().format("MM/DD/YY, HH:MM:SS")
then
updatedAt: { $gte: new Date(startDate).setHours(0,0,0,0)
$lte: new Date(endDate).setHours(0,0,0,0)},
You are declaring moment().format as a datetime but when you create Date() object you are passing only the date!
When you are practicing date manipulation better use milliseconds and UTC notation. It is something universal to all type of databases. Avoid to use varchar type to store date as strings.
Give it a try!

How to properly use $match in Mongoose?

I am using .aggregate and $match to filter dates and then $sample them. Right now I get an empty array. I am using the following code:
const result = await Event.aggregate([
{
$match: { event_added: condition },
},
{ $sample: { size: 10 } },
]);
When I use .find in the code below it works perfectly, and I get all records satisfying the condition.
const result = await Event.find({ event_added: condition });
The condition object is the following:
var condition = { $gt: start, $lt: end };
For Model.find() operations, mongoose can infer the data type based on your schema and converts the types in your query object accordingly.
So if start and end are not Date objects, mongoose will try to cast the values to Date, as specified in your Event schema.
Aggregation objects are more complex and mongoose can not automatically do type casting. If your values are not Date objects you'll have to convert them first before passing them to Model.aggregate()
Generally this should work
const condition = { $gt: new Date(start), $lt: new Date(end) }

Firebase Firestore - How to query by timestamp date?

I am trying to use a query that compares the date today as follows:
let today = Date()
cardRef.where('date', '=', today).get().then(function(cardSnapshot) {
cardSnapshot.forEach(function(doc) {
cards[doc.id] = doc.data()
})
})
Using this query, no data is fetched, is the format of the date wrong? The 'date' property is a timestamp from Firestore

Mongoose update by date without time

I'm using mongoose 4.7.x and mongodb 3.2. I want to search all date without time. E.g update all obj with this date 2016-12-14.
In my database I have multiple datetime like this :
2016-12-14 00:00:00.000Z
2016-12-14 00:00:00.000Z
2016-12-14 01:00:00.000Z
2016-12-14 01:00:00.000Z
2016-12-14 02:00:00.000Z
2016-12-14 02:00:00.000Z
I tried this :
var query = {date: new Date('2016-12-14')};
var doc = {name: 'TEST'};
var options = {multi: true};
Model.update(query, doc, options, function(err, result){
console.log('All data updated')
});
But this will just update all fields with time 00:00:00 because new Date() will returns the datetime.
How can I do to search all fields with a certain date without time ? I can change the model if it's necessary.
You can do it in between a range of dates. Use $gte for the lower range, and $lt for the higher one (which is the next day) to keep it from selecting the next day at 00:00:00 hours.
var query = {
date: {
$gte: new Date('2016-12-14'),
$lt: new Date('2016-12-15')
}
};
var doc = {name: 'TEST'};
var options = {multi: true};
Model.update(query, doc, options, function(err, result){
console.log('All data updated')
});
All documents between 2016-12-14 00:00:00.000Z and 2016-12-14 23:59:59.999Z will be updated.

Categories

Resources