所以我有这个模式
const Document = new mongoose.Schema({
_id:{
type:Number
},
creationDate:{
type:Date,
default:Date.now(),
},
title:String,
status:{
type:String,
default:status.PENDING
},
description: String,
category:[{
type:mongoose.Schema.Types.ObjectId,
ref:'Categories',
}],
})
如何找到其类别数组包含给定 ID 的文档? 我的意思是像查询一样使用类别 ID 获取所有文档
有一些方法可以实现这一点。 第一个是$elemMatch
运算符:
const docs = await Documents.find({category: { $elemMatch: {$eq: 'yourCategory'} }});
// you may need to convert 'yourCategory' to ObjectId
第二个是$in
或$all
运营商:
const docs = await Documents.find({category: { $in: [yourCategory] }});
或
const docs = await Documents.find({category: { $all: [yourCategory] }});
// you can give more categories with these two approaches
//and again you may need to convert yourCategory to ObjectId
$in
就像OR,$all
像AN。有关更多详细信息,请查看此链接:https://docs.mongodb.com/manual/reference/operator/query/all/
第三个是按aggregate()
函数:
const docs = await Documents.aggregate([
{ $unwind: '$category' },
{ $match: { 'category': mongoose.Types.ObjectId(yourCategory) } }
]};
使用 aggregate(),您可以在类别数组中只获得一个类别 ID。