Aggregate不是函数 - Mongoose Nodejs

时间:2017-10-04 00:40:14

标签: javascript node.js mongodb mongoose

有人可以帮我解决这个问题,这是我的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));
        });
    });
}}

我在控制台上收到这样的错误:

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

完成,我感谢Hana :) 我改变了我的mitraId类型ObjectId     mitraId:{        type:Schema.Types.ObjectId,         要求:是的     },

2 个答案:

答案 0 :(得分:0)

您可以在聚合语句中使用$lookup,而不是在此使用findpopulate

像这样:

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

我希望这会有所帮助。

答案 1 :(得分:0)

尽量避免查找,填充,精简功能,如下所示

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));
        });
    });
}}
相关问题