我想使用三个变量对 mongo 数据库执行查询:年龄、工作和位置作为选项。我在服务器端使用 Node 和 Express。
我写了这个:
router.post("/search", async (req, res) => {
try {
const { jobs, minAge, maxAge, location, maxDistance } = req.body;
// jobs = ["Tech", "Sales"], minAge=45, maxAge = 62, location=[1.23, 4.56], maxDistance=10000
if (!location) {
const user = User.aggregate([
{$match: {
jobs: { $or: jobs },
age: { $gte: minAge, $lte: maxAge },
}},
]).lean()
return res.json({user})
});
}
const user = User.aggregate([
{ $match: {
job: { $or: job },
age: { $gte: minAge, $lte: maxAge }
},
$geoNear: {
near: { type: "Point", coordinates: location.coordinates },
distanceField: "dist.calculated",
maxDistance,
},
},
]).lean();
return res.json({ user });
} catch (err) {
return res.json({ errorType: "search" });
}
});
如果它可能有帮助,这里是用户架构:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
age: { type: Number, min: 18 },
job: {
type: String,
enum: ["Tech", "Product", "Marketing", "Sales", "HR", "Other"],
},
location: {
type: { type: String, enum: ["Point"] },
coordinates: { type: [Number] },
},
},
{ timestamps: true }
);
userSchema.index({ age: 1, job: 1, location: "2dsphere" });
module.exports = mongoose.model("User", userSchema);
错误是MongoError:未知运算符:$or
。如何正确检索与查询中表达的条件相匹配的用户数组?
最佳答案
您需要将 job: { $or: job }
替换为 job: { $in: job }
原因 $in查询运算符根据数组验证字段的值,如果数组中至少有一个元素与字段 Vs 匹配,则获取文档 $or逻辑运算符接受两个表达式而不是值,并获取至少满足一个表达式的文档。
$在:
// jobs = ["Tech", "Sales"]
jobs: { $in: jobs }
测试: mongoplayground
$或:
{ $or: [ {jobs : 'Tech'} , {jobs : 'Sales'} ] }
测试: mongoplayground
由于您只是针对同一字段上的数组进行验证,因此不需要 $or
运算符,简单的 $in
应该可以正常工作。此外,在 $geoNear
中,您可能需要将 coordinates: location.coordinates
替换为 coordinates: location
- 我认为这是一个拼写错误。
关于node.js - Mongoose 聚合 : MongoError: unknown operator: $or,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62361529/