【问题标题】:Filter sub document array in Mongoose and return only matching elements在 Mongoose 中过滤子文档数组并仅返回匹配的元素
【发布时间】:2019-04-23 00:20:31
【问题描述】:

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案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);
        });
    });
    

    【讨论】:

    • 我们是否需要任何回调或实际返回结果的东西?因为如果我用 Postman 像这样测试它,它没有响应。我也是初学者,所以看起来很明显的东西对我来说并不明显:P
    • 有效!非常感谢 :D 另外,这个放松功能非常出色!
    • 嗨。仅将实习作为数组输出的附加代码是什么。如果我添加 $project _id: 0,并且如果我想输出数组中的所有实习,则当前代码的输出将是 [{实习:{实习对象}}] 而不是 [{实习对象}]
    • @chitgoks 你有没有设法得到那种格式
    猜你喜欢
    • 2016-07-13
    • 2019-02-16
    • 2018-05-27
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 2023-03-20
    相关资源
    最近更新 更多