Answer the question
In order to leave comments, you need to log in
How to sample from normalized forms in Mongoose?
How to select all articles with a certain tag label if the Article model instances contain only an array with the id's of the corresponding Tag model instances?
articleSchema.statics.list = function ({tag, sort, limit, skip}) {
return this
.find({
??????????????? 'tags.label': tag ???????????
})
.sort('-' + sort)
.skip(parseInt(skip))
.limit(parseInt(limit))
.populate('tags')
.exec()
};
const articleSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
body: {
type: String,
required: true
},
tags: [{
type: Types.ObjectId,
ref: 'Tag'
}],
}, {timestamps: true});
const tagSchema = new mongoose.Schema({
label: {
type: String,
required: true,
//default: 'untagged'
},
articleId:[{
type: Types.ObjectId,
ref : 'Article'
}],
},{timestamps: true});
Answer the question
In order to leave comments, you need to log in
As far as I know, it is impossible to make such a search in one query in mongo - since joins are not supported, the search can only go within the same collection.
Try to reconsider the approach, for example, denormalize the data and make another collection to associate articles with tags. Or start from tags, not from collections - that is, tags can contain links to those articles that use them.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question