简体   繁体   中英

Aggregate is not a function - Mongoose Nodejs

Can somebody help me to fix this, here is my code for aggregate from mongoose:

export class GetVehiclesbyKotaCommandHandler {
constructor(namaKota) {
    return new Promise((resolve, reject) => {
        VehiclesDB.find().populate({
            path: 'mitraId',
            model: 'RentalDB',
            select: 'namaKota'
        }).aggregate([
            {
                $match : {
                    namaKota:namaKota
                }
            }
            ]).lean().then((dataVehicles)=>{
            if(dataVehicles !== null){
                resolve(dataVehicles);
            } else {
                reject (new NotFoundException('Couldn\'t find any Vehicles with namaKota' + namaKota));
            }
        }).catch((errDataVehicles)=>{
            reject(new CanNotGetVehiclesException(errDataVehicles.message));
        });
    });
}}

And I get an error like this on the console:

TypeError: _VehiclesDB2.default.find(...).populate(...).aggregate is not a function

DONE, I Thanks for Hana :) And i change my mitraId type ObjectId mitraId : { type: Schema.Types.ObjectId, required: true },

You can use $lookup in the aggregation statement instead of using find , and populate here.

Like this:

VehiclesDB.aggregate([
    {
      $lookup: {
        from: 'RentalDB',
        localField: 'mitraId',
        foreignField: '_id',
        as: 'mitra'
      }
    }, {
      $unwind: "$mitra"
    }, {
      $match: {
        "mitra.namaKota": namaKota
      }
    }
  ])

I hope this helps.

Try to avoid find, populate, lean function here and follow as like below

export class GetVehiclesbyKotaCommandHandler {
constructor(namaKota) {
    return new Promise((resolve, reject) => {
        VehiclesDB.aggregate([
            {
              $lookup: {
                from: 'RentalDB',
                localField: 'mitraId',
                foreignField: '_id',
                as: 'mitra'
              }
            }, {
              $unwind: "$mitra"
            }, {
              $match: {
                "mitra.namaKota": namaKota
              }
            }
          ]).then((dataVehicles)=>{
            if(dataVehicles !== null){
                resolve(dataVehicles);
            } else {
                reject (new NotFoundException('Couldn\'t find any Vehicles with namaKota' + namaKota));
            }
        }).catch((errDataVehicles)=>{
            reject(new CanNotGetVehiclesException(errDataVehicles.message));
        });
    });
}}

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