如何在Mongoose中根据单个page_id筛选关联的版本数据?
问题:根据指定page_id筛选关联的版本详情
我尝试用$match条件筛选记录,但响应既没被筛选也没报错。我需要根据传入的page_id,获取所有关联的版本详情。
版本模型
const mongoose = require("mongoose"); const versionSchema = new mongoose.Schema({ version_name: { type: String, required: true }, version_slug: { type: String, required: true }, is_active: { type: Boolean, required: true }, is_deleted: { type: Boolean, required: true } }, { timestamps: true, versionKey: false }); module.exports = mongoose.model("version", versionSchema);
页面版本模型
const mongoose = require("mongoose"); const { Schema } = mongoose; const pageSchema = new mongoose.Schema({ page_id: { type: Schema.Types.ObjectId, ref: 'pages', require: true }, version_id: { type: Schema.Types.ObjectId, ref: 'versions', require: true }, }, { timestamps: true, versionKey: false }); module.exports = mongoose.model("pageVersion", pageSchema);
控制器代码
pageversions.aggregate([ { $lookup: { from: "versions", localField:"version_id", foreignField:"_id", as: "version" } }, { $unwind: "$version" }, { $project: { page_id:1, version_name: "$version.version_name", virsion_slug: "$version.version_slug", is_active: "$version.is_active" } } ]); };
当前响应
[ { "_id": "64b77c1f2712e47f8211aae2", "page_id": "64b77c1f2712e47f8211aae0", "version_name": "V2", "virsion_slug": "v2", "is_active": true }, { "_id": "64b78219a56c70b185045f7b", "page_id": "64b77c1f2712e47f8211aae0", "version_name": "V1", "virsion_slug": "v1", "is_active": true }, { "_id": "64b786251a4b4aa03e869adb", "page_id": "64b786251a4b4aa03e869ad9", "version_name": "V1", "virsion_slug": "v1", "is_active": true } ]
期望响应
[ { "_id": "64b77c1f2712e47f8211aae2", "page_id": "64b77c1f2712e47f8211aae0", "version_name": "V2", "virsion_slug": "v2", "is_active": true }, { "_id": "64b78219a56c70b185045f7b", "page_id": "64b77c1f2712e47f8211aae0", "version_name": "V1", "virsion_slug": "v1", "is_active": true } ]
解决方案
你需要在聚合管道最开始添加$match阶段,并且注意将字符串格式的page_id转换为ObjectId类型(数据库中该字段存储的是ObjectId,直接用字符串匹配会失效)。
修改后的控制器代码:
const mongoose = require("mongoose"); const ObjectId = mongoose.Types.ObjectId; // 传入的目标page_id const targetPageId = "64b77c1f2712e47f8211aae0"; pageversions.aggregate([ // 先筛选指定page_id的记录 { $match: { page_id: new ObjectId(targetPageId) } }, { $lookup: { from: "versions", localField:"version_id", foreignField:"_id", as: "version" } }, { $unwind: "$version" }, { $project: { page_id:1, version_name: "$version.version_name", version_slug: "$version.version_slug", // 修正拼写错误:virsion_slug → version_slug is_active: "$version.is_active" } } ]);
关键提示
$match放在管道最前端,先筛选再关联,能提升查询性能。- 必须转换page_id类型:数据库中
page_id是ObjectId类型,字符串无法直接匹配,这是之前筛选无效的核心原因。 - 修正投影字段的拼写错误:
virsion_slug改为version_slug,避免后续逻辑出错。
内容的提问来源于stack exchange,提问作者pradip.parkar
相关产品推荐
相关产品推荐

