简体   繁体   中英

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

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() andmore 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM