所以我有这个模式
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获取所有文档
答案 0 :(得分:1)
有一些方法可以实现这一目标。
第一个是由$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
类似于AND。有关更多详细信息,请检查以下链接:https://docs.mongodb.com/manual/reference/operator/query/all/
第三个是通过aggregate()
函数:
const docs = await Documents.aggregate([
{ $unwind: '$category' },
{ $match: { 'category': mongoose.Schema.Types.ObjectId(yourCategory) } }
]};
通过aggregate(),您只能在类别数组中获得一个类别ID。
答案 1 :(得分:0)
我相信一个简单的find查询即可。
Document.find({'category._id': 'id'}, function (err, docs) {});
或
Document.find({'category._id': 'id'})
.then(docs => {
console.log(docs)
})
.catch(error => {
console.log(error)
})
使用引用时,您可以使用_id
按其ID获取元素。
现在您可能会注意到,您只会看到ID本身。要实际查看类别中的内容,您将需要使用populate。
Document.find({
'category._id': 'id'
}).populate({
path: 'category'
}).exec((err, doc) => {
if (!err) {
console.log(doc)
} else {
console.log(err)
}
})