简体   繁体   English

聚合不是函数-Mongoose Node.js

[英]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 }, 完成,谢谢Hana :)然后我更改了mitraId类型ObjectId mitraId:{类型:Schema.Types.ObjectId,必填:true},

You can use $lookup in the aggregation statement instead of using find , and populate here. 您可以在聚合语句中使用$lookup而不是使用find ,并在此处populate

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));
        });
    });
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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