【发布时间】:2020-10-03 06:56:46
【问题描述】:
我想使用三个变量对 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: unknown operator: $or。如何正确检索与查询中表达的条件匹配的用户数组?
【问题讨论】:
-
据我了解,您需要从
array匹配jobs。然后你可以使用$in而不是$or -
我需要返回其工作是查询数组中定义的工作之一的用户。
-
@DoneDeal0 :您需要将
job: { $or: job }替换为job: { $in: job }以获得所需的结果,这里near: { type: "Point", coordinates: location.coordinates }不是coordinates: location吗?
标签: node.js mongodb express mongoose