find()中的Mongo条件属性

时间:2014-02-26 03:44:27

标签: mongodb meteor

所以在meteor中我发布了一个基于不同过滤器的集合。为了简单起见,在下面的例子中,我只有两个过滤器,但实际上我有更多。我希望能够只有一个Postings.find(),并且如果它们不是大于1,则只有属性。我怎么能做到这一点?我知道我写的代码太多了。谢谢!

Meteor.publish "PagedPostings", (deviceId, colors, capacities) ->
    ##example variables
    #deviceId= "32DLKJF334ALKDJA2"
    #colors = ["blue", "red"]
    #capacities = ["16gb", "32gb",  "64gb"]
    if colors and capacities
        postings = Postings.find(
          deviceId: deviceId
          color:
            $in: filter.colors
          condition:
            $in: filter.conditions
        )
    else if colors
        postings = Postings.find(
          deviceId: deviceId
          color:
            $in: filter.colors
        )
    else if capacities
        postings = Postings.find(
          deviceId: deviceId
          condition:
            $in: filter.conditions
        )
   return postings

1 个答案:

答案 0 :(得分:0)

Meteor.publish 'PagedPostings', (deviceId, colors, capacities) ->
  check deviceId, String
  check colors, Match.Optional [String]
  check capacities, Match.Optional [String]

  selector = {deviceId}
  selector.colorIds = $in: colors if colors
  selector.capacityIds = $in: capacities if capacities
  Postings.find selector

这需要deviceId为字符串,colorscapacities每个都是字符串数组或undefined。这似乎是基于问题的合理假设,但您可以根据实际要求轻松调整这些假设。