adamK
adamK

Reputation: 3889

MongoDB search/find by field in referenced object

I have news article and category schemas which are simplified below. I would like to be able e to return all the articles that include a given category name. Obviously I can search by a categories ObjectId _id but I would like to be able to search by category.name.

var ArticleSchema = new Schema({
    title: String,
    body: String,
    categories: [{
        type: Schema.Types.ObjectId, ref: 'Category'
    }]
});

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

Is this possible? Is it a matter of performing a search on the categories collection to return the id and then another on the articles collection to return the articles (this seems inefficient) or do I need to rework my Schema? Thanks in advance.

Upvotes: 1

Views: 403

Answers (1)

Jesus Arnaiz
Jesus Arnaiz

Reputation: 11

I don't know what data has your category collection but for me you have 2 options:

Embed category inside your article or Use custom id in category, so your category id should be your category name.

Upvotes: 1

Related Questions