【发布时间】:2015-03-20 18:13:12
【问题描述】:
我有一个管理员可以创建一个项目(波旁威士忌),用户可以在该评论中发表评论和评分。我能够聚合 cmets,但无法显示新创建的波旁威士忌,只有那些已经播种的已经有评级的。我试图实现类似于这个线程的东西:referenced thread,但我没有做正确的事情。
我是一个菜鸟,主要玩前端,我很困惑我应该如何将这个示例代码更改为实际的生产代码。我看到每个功能在做什么,但仍然模糊不清。
我应该做一个 async.each 并将聚合函数设置为迭代器..?我知道这被破坏了。我现在已经尝试了几件事。不断收到 500 错误,console.log 上没有任何内容。对这个菜鸟的任何帮助,非常感谢。
这是我的架构: 波旁威士忌:
'use strict';
var mongoose = require('mongoose'),
BourbonSchema = null;
module.exports = mongoose.model('Bourbon', {
name: {type: String, required: true},
blog: {type: String, required: true},
photo: {type: String, required: true, default:'http://aries-wineny.com/wp-content/uploads/2014/09/woodford-reserve.jpg'},
location: {type: String, required: true},
distillery: {type: String, required: true},
avgRating: {type: Number}
});
var Bourbon = mongoose.model('Bourbon', BourbonSchema);
module.exports = Bourbon;
cmets:
'use strict';
var mongoose = require('mongoose');
module.exports = mongoose.model('Comment', {
bourbonId: {type: mongoose.Schema.ObjectId, ref: 'Bourbon'},
userId: {type: mongoose.Schema.ObjectId, ref: 'User'},
text: {type: String, required: true},
createdAt: {type: Date, required: true, default: Date.now},
rating : {type: Number, required: true},
votes: {type: Number, default: 0}
});
这是我在控制器中的查找/获取,我尝试从引用的链接拼凑起来,但现在草率了:
'use strict';
var Bourbon = require('../../../models/bourbon'),
Comment = require('../../../models/comment'),
DataStore = require('nedb'),
db = new DataStore(),
async = require('async');
module.exports = {
description: 'Get Bourbons',
notes: 'Get Bourbons',
tags: ['bourbons'],
handler: function(request, reply){
async.waterfall(
[
function(comment,callback){
async.series(
[
function(callback){
Bourbon.find({},function(err,results){
async.eachLimit(results,10,function(result,callback){
db.insert({
'bourbonId': result._id.toString(),
'location' : result.location,
'blog' : result.blog,
'distillery': result.distillery,
'name': result.name,
'avgRating': 0
},callback);
},callback);
});
},
function(callback){
Comment.aggregate(
[
{'$group':{
'_id': '$bourbonId',
'avgRating':{
'$avg':'$rating'
}
}}
],
function(err,results){
async.eachLimit(results,10,function(result,callback){
db.update(
{'bourbonId': result._id.toString()},
{'$set':{
'avgRating': result.avgRating
}
},
callback
);
},callback);
}
);
}
],
function(err) {
if (err) callback(err);
db.find({},{'_id': 0},callback);
}
);
}
],
function(err,results){
reply({results: results});
console.log('LOOOOOOOOOOOOOOOOK',JSON.stringify(results, undefined, 4));
process.exit();
});
}
};
【问题讨论】:
-
尝试一次只关注其中的一部分。你已经破坏了所有的服务器代码,所以只需在一个单独的隔离区域中使用,直到你做对为止。你在这里错位了很多。这些操作应该是“系列”而不是“瀑布”,因为你没有传递任何东西。他们还需要包装函数定义以传递回调以继续下一个。简而言之,您误解并从您复制的内容中删减了太多内容。
-
好的。我会这样做的。
-
这个更新的编辑是我所拥有的。我得到了 200,但结果没有任何 console.logs
-
文档还应该返回一个空数组吗?
标签: javascript node.js mongodb mongoose