猫鼬聚合:MongoError:未知运算符:$ or

时间:2020-06-13 15:00:21

标签: node.js mongodb express mongoose

我想对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。如何正确检索符合查询条件的用户数组?

2 个答案:

答案 0 :(得分:2)

您需要将job: { $or: job }替换为job: { $in: job },原因是$in查询运算符针对数组验证字段的值,并且如果数组中至少有一个元素与字段 Vs $or逻辑运算符接受两个表达式而不是值,并获取至少满足一个表达式的文档。

$ in:

// jobs = ["Tech", "Sales"]

jobs: { $in: jobs }

测试: mongoplayground

$ or:

{ $or: [ {jobs : 'Tech'} , {jobs : 'Sales'} ] }

测试: mongoplayground

当您只是针对同一字段上的数组进行验证时,不需要$or运算符,简单的$in应该可以正常工作。此外,在$geoNear中,您可能需要将coordinates: location.coordinates替换为coordinates: location-我认为这是一个错字。

答案 1 :(得分:0)

$or is an expression-level operator,而不是字段级运算符。等于$ or的字段级别为$in