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

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

最佳答案

您可以尝试我的代码:

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

关于javascript - 在 Mongoose 中过滤子文档数组并仅返回匹配的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53394985/

相关文章:

java - 使用 Java/Groovy 读取 MongoDB oplog

javascript - 带三 Angular 形的 masonry 网格?

javascript - 将 ajax arraybuffer 响应绘制到 Canvas 中

node.js - 如何构建用于测试的 meteor 应用程序

mysql - NodeJS MySQL 检查多个

Mongodb:如何使用一个查询获取不同集合中文档的数量?

javascript - 找到相同的id并将它们存储到一个数组中

javascript - 将 Node 路由与 Backbone 路由绑定(bind)

javascript - Angular 2 Karma Test 'component-name' 不是已知元素

mongodb - 为什么下面的 mongodb 组查询总是返回 0?