问题
so i have this schema
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',
}],
})
how do i find documents that their category array contains an id given ? i mean like a query to get all documents using category id
回答1:
There are some ways to achieve this.
First one is by $elemMatch
operator:
const docs = await Documents.find({category: { $elemMatch: {$eq: 'yourCategory'} }});
// you may need to convert 'yourCategory' to ObjectId
Second one is by $in
or $all
operators:
const docs = await Documents.find({category: { $in: [yourCategory] }});
or
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
is like OR and $all
like AND. For further details check this link : https://docs.mongodb.com/manual/reference/operator/query/all/
Third one is by aggregate()
function:
const docs = await Documents.aggregate([
{ $unwind: '$category' },
{ $match: { 'category': mongoose.Schema.Types.ObjectId(yourCategory) } }
]};
with aggregate() you get only one category id in your category array.
回答2:
I believe a simple find query would do.
Document.find({'category._id': 'id'}, function (err, docs) {});
or
Document.find({'category._id': 'id'})
.then(docs => {
console.log(docs)
})
.catch(error => {
console.log(error)
})
When you use reference then you can get elements by their ids with _id
.
Now you may notice that you will only see the id itself. To actually see what is in the category, you will need to use populate.
Document.find({
'category._id': 'id'
}).populate({
path: 'category'
}).exec((err, doc) => {
if (!err) {
console.log(doc)
} else {
console.log(err)
}
})
来源:https://stackoverflow.com/questions/63368225/mongoose-find-documents-if-array-contains-a-value