【问题标题】:mongodb distinct() implementation in Meteor on the server?服务器上 Meteor 中的 mongodb distinct() 实现?
【发布时间】:2026-02-03 01:55:01
【问题描述】:

我需要从 Meteor 中的 mongodb 获取不同的值(基本上,实现 mongodb 本机 distinct() 调用)。在客户端,Does Meteor have a distinct query for collections? - 这就像一个魅力。但我不知道如何在服务器端获得类似的工作。感谢任何帮助。谢谢!

【问题讨论】:

标签: mongodb meteor


【解决方案1】:

好吧,在对代码进行了一些挖掘并意识到 mongo lib 包含所有需要的方法的本机实现之后,我重用了来自 https://github.com/meteor/meteor/pull/644 的 aggregate() 解决方案

直接更改和转换为coffeescript 将以下sn-p 放入您的服务器端代码中:

path = __meteor_bootstrap__.require("path")
MongoDB = __meteor_bootstrap__.require("mongodb")
Future = __meteor_bootstrap__.require(path.join("fibers", "future"))

myCollection = new Meteor.Collection "my_collection"

#hacky distinct() definition from https://github.com/meteor/meteor/pull/644
myCollection.distinct = (key)->
  future = new Future
  @find()._mongo.db.createCollection(@_name,(err,collection)=>
    future.throw err if err
    collection.distinct(key, (err,result)=>
      future.throw(err) if err
      future.ret([true,result])
      )
    )
  result = future.wait()
  throw result[1] if !result[0]
  result[1]

缺点是您必须为每个新集合定义它,但这很容易通过 _.extend 或我猜的其他方式修复...

PS 它现在也是一个智能包 - mrt add mongodb-aggregation

【讨论】:

  • 我正在使用meteor 0.8.2,并且必须进行以下替换才能使用此代码meteor_bootstrap => Npm,future.ret => future.return。要求 mongodb 似乎是不必要的。我会使用这个包,但是它缺乏对用户身份验证的支持,使得底层集合完全开放。
【解决方案2】:

如果有人在 Meteor v1.0+ (1.0.2) 中尝试这个,这个代码对我有用,我把它放在服务器上。与提到调整的 J Ho 的答案基本相同 - Npm.require 以及 Future['return']。为那里的 Coffeescripters 清理了一点。

我正在考虑这个包,但已经有了meteorhacks:aggregate 包(只有aggregate 功能),因此不想用另一个包覆盖它。所以,我只是在其他人的帮助下推出了自己的distinct

希望这对某人有所帮助!最有可能的是,如果我继续在更多集合上使用 distinct,我将使用 _.extend Meteor.Collection 就像这里:https://github.com/zvictor/meteor-mongo-server/blob/master/server.coffee

path = Npm.require('path')
Future = Npm.require(path.join('fibers', 'future'))

myCollection = new Meteor.Collection "my_collection"

myCollection.distinct = (key, query) ->
  future = new Future
  @find()._mongo.db.createCollection @_name, (err,collection) =>
    future.throw err if err

    collection.distinct key, query, (err,result) =>
      future.throw(err) if err
      future['return']([true,result]) 

  result = future.wait()
  throw result[1] if !result[0]
  result[1]

【讨论】: