Hello, I’m trying to make a request for my forum, I’ve worked with date for the schema.find without problem but can’t make it work with aggregate, can someone help me please ?
//Get Post Number By Category and range of Day
module.exports.postCatDate_GET = async (req, res) => {
const day = parseInt(req.query.day); // ?day=100
try {
var posts = await Post.aggregate([{
createdAt: {
"$gte": ISODate(new Date(new Date() - day * 60 * 60 * 24 * 1000)),
},
"$group": {
_id: "$categoryId",
count: {
$sum: 1
}
}
}])
res.status(200).json(posts);
} catch (err) {
res.status(500).json(err);
}
}
The group part work but I can’t add the date search like in find, I’ve read a lot about ISODate but keep the internal error.
Hello @Virgil_Nauleau, Welcome to the MongoDB Community forum!
First, there are syntax errors in your aggregation pipeline. Each stage is to be within a set of braces { ... }. And, each stage has a stage name like, $match, $group, $project, etc.
You define stages like this and build the pipeline, and then run the query:
var match_stage = {
$match: {
createdAt: { $gte: { .... } }
}
}
var group_stage = {
$group: {
_id: "$categoryId",
count: { $sum: 1 }
}
}
var pipeline = [ match_stage, group_stage ]
var posts = await Post.aggregate(pipeline)
// ... rest of your code here
Thank you so much !!! T.T It perfectly work, kinda remind me Prepare table of sqlite using Golang
I think I will make var like that more often for my agregate
At first i though it was a necessary cast because everyone does it (from forum I’ve seen from my problem) but resulting in changing absolutely nothing that’s why I was asking
Folks, when working with a NodeJS application (using MongoDB NodeJS Driver or Mongoose ODM), use the JavaScript Date. ISODate is for mongo shell (see my previous comment links).