首页 > 解决方案 > 在 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
      }
    }
  );
});

标签: javascriptnode.jsmongodbmongoose

解决方案


你可以试试我的代码:

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);
    });
});

推荐阅读