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

Sei*_*eld 1 javascript mongoose mongodb node.js

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]
});
Run Code Online (Sandbox Code Playgroud)

可以看出,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
      }
    }
  );
});
Run Code Online (Sandbox Code Playgroud)

hoa*_*gdv 6

你可以试试我的代码:

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);
    });
});
Run Code Online (Sandbox Code Playgroud)