0

I have an existing News articles section that I want to add categories to for more refined searching, my Schema's are as follows:

var ArticleSchema = new Schema({
title: String,
body: String,
author: {
    type: Schema.Type.ObjectId,
    ref: 'User',
    required: true
},
image: String,
catagories: [{
    type: Schema.Types.ObjectId, ref: 'Catagory'
}],
meta: {
    created: {
        type: Date,
        'default': Date.now,
        set: function(val) {
            return undefined;
        }
    },
    updated: {
        type: Date,
        'default': Date.now
    }
}
});

ArticleSchema.statics.search = function (str, callback) {
var regexp = new RegExp(str, 'i');
return this.find({'$or': [{title: regexp}, {body: regexp}]}, callback);
};

module.exports = ArticleSchema;


var CatagorySchema = new mongoose.Schema({
name: { type: String, unique: true },
});

module.exports = CatagorySchema;

I want a user friendly input for selecting categories (don't even know what is best here, be it check-box's or a simple comma separated text input etc.). My question is what is the best practice for obtaining this kind of input and translating that into the Article Schema (providing the categories exist). If anyone could point me in the right direction it would be much appreciated. Thanks.

1 Answer 1

0

Keep the category names you want to search for in an array

{
  categories: ["cat1", "cat2"]
}

then you can add an index to it and do a $in query. the current schema is not very good because you cannot look for the category in a single query but need to resolve all the "categories" links first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.