Search code examples
node.jsmongodbaggregatemongo-shell

using aggregation MongoDB


I'm trying to use .aggregate() with other mongo shell methods and i got UnhandledPromiseRejectionWarning: TypeError: User.find(...).select(...).sort(...).aggregate is not a function

const users = await User
            .find(findParams)
            .select(userResponse)
            .sort(sortParams)
            .aggregate(([
                {
                    $project:{
                        dateCreated: {$dateToString: {format: "%G-%m-%d %H:%M:%S", date: "$dateCreated"}},
                    }
                }
            ]))
            .exec()

BUT, when i use .aggregate() without other methods it works perfect.

const users = await User
            .aggregate(([
                {
                    $project:{
                        dateCreated: {$dateToString: {format: "%G-%m-%d %H:%M:%S", date: "$dateCreated"}},
                    }
                }
            ]))
            .exec()

Can i insert it with other methods but without getting this error. Thanks


Solution

  • In the first block of code, you are trying to apply db.collection.aggregate() method on a cursor which is returned by find() method. Cursors are which basically returned from collection methods like find(), aggregate() and more here.

    In the second code block, you are directly applying aggregate() on the User collection. That's why it is working. And yes, you can do whatever select, sort, limit using aggregate() even without using those cursor methods here. Hope this will help, Dude. Have a great day!

    MongoDB documentation page screenshot