如果我尝试从为 mongodb 创建的聚合中获取用户,则会收到错误。
const users = await locations.aggregate([
{
$geoNear: {
near: {
type: "Point",
coordinates: [req.query.longitude, req.query.latitude],
},
maxDistance: 2000,
distanceField: "dist.calculated",
spherical: true,
},
},
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user",
},
},
{
$replaceRoot: {
newRoot: {
$arrayElemAt: ["$user", 0],
},
},
},
{
$project: {
_id: 1,
userId: 1,
name: 1,
profession: 1,
hide: 1,
profilePhotoLink: 1,
uid: 1,
},
},
{
$limit: pageSize,
},
{
$skip: pageSize * (req.query.page - 1),
},
]);
它工作正常,我将用户放入数组中,但现在它抛出一个错误。
错误:
code: 500,
error: 'Server Error',
api: '/api/users?longitude=77.3720925&latitude=28.6851771&distance=250&page=1',
level: 'error',
message: MongoServerError: PlanExecutor error during aggregation :: caused by :: 'newRoot' expression must evaluate to an object, but resulting value was: MISSING. Type of resulting value: 'missing'. Input document: {_id: 64c4bfc46c4590160ec0e6cc, userId: 64c4bfb66c459012fac0e6c6, location: {coordinates: [180.3721, 21.6852], type: "Point"}, createdAt: 2023-07-29T07:29:08.311Z, updatedAt: 2023-07-29T07:29:08.311Z, __v: 0, dist: {calculated: 2.12997}, user: []}
我不知道为什么失败以及如何解决它?
最佳答案
我猜这是因为对于某些特定的过滤器( longitude=77.3720925&latitude=28.6851771&distance=250
),数据库中不存在用户,因此在 $lookup
之后有空数组下一步失败并返回 500。
也许您可以简单地使用 $match
进行过滤。没有找到任何用户的点:
const users = await locations.aggregate([
{
$geoNear: {
near: {
type: "Point",
coordinates: [req.query.longitude, req.query.latitude],
},
maxDistance: 2000,
distanceField: "dist.calculated",
spherical: true,
},
},
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user",
},
},
{
$match: {
"user.0": {
"$exists": true
}
}
},
{
$replaceRoot: {
newRoot: {
$arrayElemAt: ["$user", 0],
},
},
},
{
$project: {
_id: 1,
userId: 1,
name: 1,
profession: 1,
hide: 1,
profilePhotoLink: 1,
uid: 1,
},
},
{
$limit: pageSize,
},
{
$skip: pageSize * (req.query.page - 1),
},
]);
关于node.js - MongoServerError:聚合期间的 PlanExecutor 错误::由::'newRoot' 表达式引起,表达式必须计算为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76792829/