Raven Dreamer
Raven Dreamer

Reputation: 7140

Is it possible to condense arrays in a mongoose query?

I have the following schemas

var book_s = new Schema({
        //_id: automatically generated,
        pageCount: Number,
        titles: [{ type: Schema.Types.ObjectId, ref: 'BookTitle' }]
    });

var bookTitle_s= new Schema({
        //_id: automatically generated,
        language: String,
        title: String
});

If I use a query like the following: Book.find({}).populate('titles').exec()

I will get a list of all titles for each book.

Is there a way to alter the query so that I can pass in a language paramater (say, English), and populate only the English titles into the Book model?

Upvotes: 0

Views: 47

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You can use a match field in your populate call to only populate those models that pass its conditions:

Book.find({}).populate({path: 'titles', {match: {language: 'English'}}}).exec()

Upvotes: 1

Related Questions