如何通过分类ID数组筛选Mongoose中的Product模型数据
问题描述
我有以下两个Mongoose模型:
Product模型
const productSchema = new mongoose.Schema({ categories:{ type: mongoose.Schema.Types.ObjectId, ref: 'Category' } })
Category模型
const categorySchema = new mongoose.Schema({ title: { type: String, required: true } })
现在我需要通过请求体传入的分类ID数组(例如["_1234464" , "_987654321"])筛选产品,在controller/products的代码中,需要补充productModel.find的查询条件:
exports.get = async (req, res, next) => { const categories = req.body.categories; // 格式如 [_1234464 , _987654321] const filteredProducts = productModel.find({ /* 这里需要补充查询条件 */ }) })
请补充查询条件实现按分类ID数组筛选产品。
解决方案
直接用Mongoose的$in操作符就能实现这个需求,它可以匹配字段值存在于指定数组中的所有文档。另外要注意,要是请求里传的分类ID是字符串格式,得先转成Mongoose的ObjectId类型,不然匹配不上。
补全后的代码如下:
exports.get = async (req, res, next) => { try { const categories = req.body.categories; // 把字符串ID转成ObjectId数组 const categoryIds = categories.map(id => mongoose.Types.ObjectId(id)); const filteredProducts = await productModel.find({ categories: { $in: categoryIds } }); res.status(200).json(filteredProducts); } catch (err) { next(err); } })
关键点说明:
$in操作符的作用就是筛选出categories字段值在categoryIds数组里的所有产品- 必须转换ID类型:Mongoose存储的
ObjectId是特殊类型,字符串ID不转的话没法匹配 - 加个
try/catch能捕获无效ID格式这类错误,避免程序崩掉
额外提示
如果你的categories字段其实是数组(比如一个产品能属于多个分类),这个查询逻辑也能用,$in会匹配那些分类数组里包含任意目标ID的产品。
内容的提问来源于stack exchange,提问作者morteza mortezaie
相关产品推荐
相关产品推荐

