下面是我的发布函数,它几乎是 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/