Reputation: 1670
I am having trouble wrapping my head around how to implement the following:
I have a MongoDB Schema like so:
var DocumentSchema = new Schema({
num: Number,
authors: [String]
})
Which is being used for the backend for a Backbone collection. I am having trouble understanding how to filter through each document's authors
array to match a username.
Something like:
var DocumentCollection = Backbone.Collection.extend({
model: Document,
match_username: function() {
var username = 'foo'
// match username to author...
})
}
});
To summarize, I would be filtering through the authors
array for each document in the collection to check if there is a username match. If the username matches, get num
and store in a new array to be returned.
What is the most efficient way of going about this?
Upvotes: 0
Views: 173
Reputation: 18462
If I understand you correctly, it sounds like what you need is:
var DocumentCollection = Backbone.Collection.extend({
model: Document,
match_username: function() {
var username = 'foo'
return this.chain().filter(function(doc) {
return _.indexOf(doc.get('authors'), username) > -1;
}).map(function(doc) {
return doc.get('num');
}).value();
}
});
It's filtering using _.indexOf
on the authors
, then _.map
on the num
of the filtered collection.
Upvotes: 1