W
W
wini6662017-08-26 01:00:05
MongoDB
wini666, 2017-08-26 01:00:05

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()
};

Article Model
const articleSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },

    body: {
        type: String,
        required: true
    },

    tags: [{
        type: Types.ObjectId,
        ref: 'Tag'
    }],

}, {timestamps: true});

Tag Model
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

1 answer(s)
P
Ptolemy_master, 2017-08-26
@wini666

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 question

Ask a Question

731 491 924 answers to any question