0

这是我在 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[ name ]=provincia de Barcelona

按预期返回过滤结果:

[
    {
        "_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

返回这个:

{
    "message": ""
}

并且 console.log(err) 返回这个:

[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"
    }
]
4

1 回答 1

0

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

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"
    }
]

于 2015-01-19T19:19:28.523 回答