在Mongoose中过滤子文档数组,仅返回匹配的元素

时间:2018-11-20 14:16:58

标签: javascript node.js mongodb mongoose

我有UserSchema像这样

const userSchema = mongoose.Schema({
  email: {
    type: String,
    trim: true,
    required: true,
    unique: 1
  },
  password: {
    type: String,
    required: true,
    minlength: 6
  },
  token: {
    type: String
  },
  role: {
    type: Number,
    default: 0 // 0 is student, 1 is admin
  },
  files: [FileSchema],
  internships: [InternshipSchema]
});

可以看出,filesinternships是子文档。我的目标是根据特定的输入条件过滤其中任何一个,例如,我想根据国家/地区过滤实习机会。

但是,我有一个问题,仅返回与搜索匹配的元素,无论传入的搜索过滤器如何,我都只能返回所有元素。

我尝试引用querying-subdocument-and-returning-matching-subdocument-only,但无法使其正常工作。

我当前的代码如下

app.get("/api/getInternships", (req, res) => {
  User.aggregate(
    {
      $match: {
        "internships.country": req.query.country
      }
    },
    { $unwind: "internships" },
    {
      $match: {
        "internships.country": req.query.country
      }
    }
  );
});

1 个答案:

答案 0 :(得分:1)

您可以尝试我的代码:

app.get("/api/getInternships", (req, res) => {
    User.aggregate(
        { $project: { internships: 1 } },
        // after $project
        /* 
        {_id: ObjectId01, internships: [{country: 1}, {country: 2},...]}
        ....
         */
        { $unwind: '$internships' },
        // after $unwind
        /* 
        {_id: ObjectId01, internships: {country: 1}}
        {_id: ObjectId01, internships: {country: 2}}
        ...
         */
        {
            $match: {
                "internships.country": req.query.country
            }
        }
        // final result: [{_id: ObjectId01, internships: {country: 2}}, ...]
    ).exec((err, internships) => {
        if (err) throw err;
        console.log(internships);
        // [{_id: ObjectId01, internships: {country: 2}}, ...]
        // send data to client
        res.status(200).json(internships);
    });
});