javascript - 在 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]
});
可以看出files
和internships
都是子文件。我的目标是根据特定输入过滤其中任何一个,例如,我想根据国家/地区过滤实习。
但是,我遇到了仅返回与搜索匹配的元素的问题,我只能返回所有元素,而不管传入的搜索过滤器如何。
我试图引用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);
});
});
推荐阅读
- android - 如何修复:Recyclerview 未显示在 Activity 中
- java - 为什么操作系统说内存足够时无法为jvm分配内存
- javascript - 如何排除 Firebase 数据库树中的某些键
- dataframe - 将 Julia DataFrames 列表写入文件
- certificate - 在 WCF 自定义发送适配器上设置 clientCredentials 端点行为
- typescript - 打字稿无法推断函数参数
- webpack-4 - 具有自己的块依赖项的动态模块导入
- python - 无法更改数组某些部分的值
- android - 如果服务器是 apollo graphql 服务器,从 android 应用程序上传文件的最佳方式是什么
- jenkins - Kotlin 在本地机器上正确编译项目,但通过 Jenkins 它抛出异常