Thursday, 18 May 2017

Mongoose: Find all courses by it`s category name

I have the following schemas in mongoose:

course.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const courseSchema = new Schema({
    tag: {
        type: String,
        required: true
    },
    title: {
        type: String,
        required: true
    },
    summary: {
        type: String,
        required: true
    }
    category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category'
    }
});
module.exports = mongoose.model('Course', courseSchema);

category.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const categorySchema = new Schema({
    slug: {
        type: String,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    image: {
        type: String,
        required: true
    }
});
module.exports = mongoose.model('Category', categorySchema);

When I try to find my courses by it`s category name, it does not works.

exports.getByCategory = async (category) => {
    const res = await Course.find(
        {
            active: true,
            'category.name': category
        },
        "tag title summary image level duration category lastUpdateDate averageReview views price")
        .populate('category', 'name')
        .sort('-lastUpdateDate');
    return res;
}

Can someone please give me bet here? I`m using 'category.name' on my query, as the mongoose documentation tells me to.. but...

Thanks



via Andre Baltieri

No comments:

Post a Comment