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[コミュニティ]=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 に答える