how to get a model by array params from a collection

I have a model like this:

model = 
    from: "a@b.com"
    id: 1
    to: [c@d.com]

and I have a collection containing these kind of models. The collection needs to filter by from. I know _.where an underscore.js function. I am using it like this:

fromIds = _.pluck _.where(msgs, from : login), 'msgId' 

and need to filter by 'to' as well:

toIds = _.pluck _.where(msgs, to : login), 'msgId' 

it does not work, because to is an array. How can I filter by to ? I would be grateful if someone helped me out !

Answers


At that point you need to use _.filter. If you look at the source code you can see that _.where is just a helpful wrapper around _.filter. _.where is good for simple filtering based on primitive comparison, but anything more complex you will have to write yourself.

# Filter for messages that contain the target address.
matchedTo = _.filter msgs, (msg) -> _.contains msg.to, login

# Pluck as usual
toIds = _.pluck matchedTo, 'msgId'

Need Your Help

XML referencing to an id with # or not?

xml reference identifier xpointer

My current project consists of letters which are in collections. Each collection has an id and the letters refer to these ids.

mongoid array with blanks

ruby-on-rails ruby-on-rails-3 mongodb mongoid

I'm using a an array in mongoid to store user roles and it mostly works fine, but I have the problem with rails passing in a blank to an array and mongoid saves it.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.