'mongoose debug do not format ObjectId in aggregate method
I try to enable debug in mongoose
mongoose.set('debug', true)
And then every query will show in the console with colors like that
users.findOne({ _id: ObjectId("61babeae3e6086973a71f0d1")})
But when I use aggregate method, the result like that
users.aggregate([ { '$match': {_id: {$in: [61babeae3e6086973a71f0d1]}}])
How can I format ObjectId? Same issue with Date value
Solution 1:[1]
Mongoose automatically uses string values as ObjectId in its find, update, delete, and other regular queries. However, this is not the case for aggregation pipeline queries. So, you have to manually cast the string ObjectIds as:
users.aggregate([
{
$match: {
_id: {
$in: [mongoose.Types.ObjectId('61babeae3e6086973a71f0d1')]
}
}
}
])
This is described in issue #1399 here: https://github.com/Automattic/mongoose/issues/1399
For Date values, use them in $match stage as:
users.aggregate([
{
$match: {
createdAt: {
$gte: new Date('2021-08-06T07:50:29.279')
}
}
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bibhu96 |
