MongoDB Aggregation 添加下一个文档(一个 Meteor App)

标签 mongodb meteor

下面是我的发布函数,它几乎是 Average Aggregation Queries in Meteor 的副本

用途:显示文档列表。然后用户可以单击一项(餐厅)并可以查看详细信息。在详细信息中有上一个和下一个箭头,可以在列表中循环。

我的想法是使用该聚合方法通过上一个和下一个文档 ID 丰富每个文档,这样我就可以轻松构建我的上一个和下一个链接。

但是怎么办?我不知道。也许有更好的方法?

Meteor.publish("restaurants", function(coords, options) {
    if (coords == undefined) {
        return false;
    }
    if (options == undefined) {
        options = {};
    }
    if (options.num == undefined) {
        options.num = 4
    }
    console.log(options)
    /**
     * the following code is from https://stackoverflow.com/questions/18520567/average-aggregation-queries-in-meteor
     * Awesome piece!!!
     * 
     * */
    var self = this;
    // This works for Meteor 1.0
    var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;

    // Your arguments to Mongo's aggregation. Make these however you want.
    var pipeline = [
        {
         $geoNear: {
            near: { type: "Point", coordinates: [ coords.lng , coords.lat ] },
            distanceField: "dist.calculated",
            includeLocs: "dist.location",
            num: options.num,
            spherical: true
         }
       }
    ];

    db.collection("restaurants").aggregate(        
        pipeline,
        // Need to wrap the callback so it gets called in a Fiber.
        Meteor.bindEnvironment(
            function(err, result) {
                // Add each of the results to the subscription.
                _.each(result, function(e) {
                    e.dist.calculated = Math.round(e.dist.calculated/3959/0.62137*10)/10;
                    self.added("restaurants", e._id, e);
                });
                self.ready();
            },
            function(error) {
                Meteor._debug( "Error doing aggregation: " + error);
            }
        )
    );
});

最佳答案

如果您没有很多关于结果的文档,您可以使用 JavaScript 来完成。将您的订阅代码更改为类似这样的内容(我没有测试此代码)。

_.each(result, function(e, idx) {
  if(result[idx - 1]) e.prev = result[idx - 1]._id;
  if(result[idx + 1]) e.next = result[idx + 1]._id;
  e.dist.calculated = Math.round(e.dist.calculated/3959/0.62137*10)/10;
  self.added("restaurants", e._id, e);
});

关于MongoDB Aggregation 添加下一个文档(一个 Meteor App),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26861070/

相关文章:

mongodb - MongoDB 中好的分片键

javascript - 如何将所有 Meteor Mongo 集合名称检索为 Javascript 数组?

javascript - 在 Mongoose 中间件方法 pre save 和 post save 之间共享数据

javascript - Node.js 或 Ubuntu Linux 在服务器启动时运行 cron

arrays - mongodb跨文档查找数组中的重复项

mongodb - 有没有办法获得 Mini Mongo 的 GUI 表示?

javascript - 方法在 API 请求上使用哪个 IP(用户或服务器)?

java - Spring MongoDB 进程/线程泄漏

javascript - 在 Meteor 的 Collection 中定义值数组

javascript - setState 不适用于 React 和 Meteor 中的 UI 更改