MEAN.JS: mongoose 中间件中的过滤器

MEAN.JS: Filter in mongoose middleware

这是我在 MEAN JS 后端控制器中的代码:

exports.list = function(req, res) {
    // configure the filter using req params
    var filters = {
        filters : {
            optional : {
                contains : req.query.filter
            }
        }
    };

    var sort = {
        asc : {
            desc: 'name'
        }
    };

    Province
        .find()
        .filter(filters)
        .order(sort)
        .exec(function (err, provinces) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.jsonp(provinces);
            }
        });


};

要求:

http://localhost:3000/provinces?filter[名称]=巴塞罗那省

Returns 过滤后的结果,符合预期:

[
    {
        "_id": "54ba72903f51d73c4aff6da6",
        "community": "54ba689f5fdfbdea292b8737",
        "location": "{lat: '41.386290', lng: '2.184988', zoom: '11'}",
        "__v": 0,
        "name": "provincia de Barcelona"
    }
]

当我使用不同的属性时,过滤器停止工作。示例:

http://localhost:3000/provinces?filters[社区]=54ba69755fdfbdea292b8738

Return这个:

{
    "message": ""
}

和console.log(错误)return这个:

[CastError: Cast to ObjectId failed for value "/54ba689f5fdfbdea292b8737/i" at path "community"]
  message: 'Cast to ObjectId failed for value "/54ba689f5fdfbdea292b8737/i" at path "community"',
  name: 'CastError',
  type: 'ObjectId',
  value: /54ba689f5fdfbdea292b8737/i,
  path: 'community' }

原文档:

[
    {
        "_id": "54ba72903f51d73c4aff6da6",
        "community": "54ba689f5fdfbdea292b8737",
        "location": "{lat: '41.386290', lng: '2.184988', zoom: '11'}",
        "__v": 0,
        "name": "provincia de Barcelona"
    },
    {
        "_id": "54ba73c33f51d73c4aff6da7",
        "community": "54ba69755fdfbdea292b8738",
        "location": "{lat: '42.4298846', lng: '-8.644620199999963', zoom: '11'}",
        "__v": 0,
        "name": "provincia de Pontevedra"
    }
]

也许这不是最好的方法,但有效:)

exports.list = function(req, res) {

 var community = {community: ''};
 community.community = mongoose.Types.ObjectId(req.query.filter.community);
 console.log(community);

 var filters = {
  filters : {
   optional : {
    contains : community
   }
  }
 };



 var sort = {
  asc : {
   desc: 'name'
  }
 };

 Province
  .find()
  .filter(filters)
  .order(sort)
  .exec(function (err, provinces) {
   console.log(err);
   if (err) {
    return res.status(400).send({
     message: errorHandler.getErrorMessage(err)
    });
   } else {
    res.jsonp(provinces);
   }
  });


};

要求:

http://localhost:3000/provinces?filter[community]=54ba689f5fdfbdea292b8737

结果:

[
    {
        "_id": "54ba72903f51d73c4aff6da6",
        "community": "54ba689f5fdfbdea292b8737",
        "location": "{lat: '41.386290', lng: '2.184988', zoom: '11'}",
        "__v": 0,
        "name": "provincia de Barcelona"
    }
]