我正在尝试从用户位置+用户选择的类别列表中进行查询。由于$ geoNear不接受两个参数。我一直在尝试从返回值进行查询。但是,我收到一条错误消息,说我无法对JSON格式文件(不是函数)执行.find()。
static async getuserinitialplace(favCatgories, userCoordinates) {
console.log(userCoordinates);
try {
const places = await Place.aggregate([
{
$geoNear: {
near: { type: 'Point', coordinates: userCoordinates },
distanceField: 'calcDistance',
maxDistance: 25000,
spherical: true,
},
},
{ $limit: 200 },
]);
return places;
} catch (err) {
return console.log(err);
}
}
我还尝试将其放在函数内部,然后出现回调错误和其他错误。
static async getuserinitialplacea(req, res) {
const result = await PlaceService.getuserinitialplacea(
JSON.parse(req.query.userCoordinates),
).find({category: req.query.favCatgories})
res.send(result)
}
在使用$ geoNear时,是否还有两个参数可以查询?
答案 0 :(得分:1)
尝试在变量中为getuserinitialplace
编写两个args,然后将它们用作args,如下所示:
static async getuserinitialplacea(req, res) {
try {
let arg = JSON.parse(req.query.userCoordinates);
const result = await PlaceService.getuserinitialplace(arg)
res.send(result)
} catch (e) {
console.error(e)
}
}
此.find({category: req.query.favCatgories})
查找部分也没有意义。聚合doesn't return you a Mongoose Document or a Mongoose Model。
如果您的函数应将your用作第二个参数,则使用它,如下所示:
let arg = JSON.parse(req.query.userCoordinates);
let another_arg = req.query.favCatgories;
const result = await PlaceService.getuserinitialplace(arg, another_arg )
甚至更好:
/** Code */
const { userCoordinates, favCatgories} = req.query;
const result = await PlaceService.getuserinitialplace(favCatgories, userCoordinates)
/** Other code */
如果您想在$geoNear
之后找到一些东西,只需添加$match
另一个阶段并进行查询。像这样:
static async getuserinitialplace(favCatgories, userCoordinates) {
console.log(userCoordinates);
try {
const places = await Place.aggregate([
{
$geoNear: {
near: { type: 'Point', coordinates: userCoordinates },
distanceField: 'calcDistance',
maxDistance: 25000,
spherical: true,
},
},
/** You could also add it before $geoNear stage */
{ $match: { nameOfField: favCatgories } },
/** OR { $match: favCatgories }, */
/** BUT favCatgories should be an object */
{ $limit: 200 },
]);
return places;
} catch (err) {
return console.log(err);
}
}