我正在使用express.js,mongoose,jquery和socket.io
我正在尝试传递对象" allFightScores"客户端上的套接字。这是我在routes / index.js中从mongoose请求信息的地方:
var models = require('../models/index.js');
var passport = require('passport');
var crawl = require('../crawler.js');
var flash = require('connect-flash');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
exports.submit_scores = function(req, res){
var scored_fight = new models.UserScore({
"f1": req.body.f1,
"f2": req.body.f2,
"f1_roundScores": req.body.f1_roundScores,
"f2_roundScores": req.body.f2_roundScores,
"f1_score": req.body.f1_score,
"f2_score": req.body.f2_score,
"user_email": req.body.user_email
});
models.UserScore.find({
"f1": scored_fight.f1,
"f2": scored_fight.f2,
"f1_score": scored_fight.f1_score,
"f2_score": scored_fight.f2_score,
"user_email": scored_fight.user_email
}, function(err, data){
if (data.length === 0){
scored_fight.save(function(err, user_fight){
if (err) {
return "error";
}
else {
models.UserScore.find({"f1": user_fight.f1, "f2": user_fight.f2}, function(err, allFightScores){
console.log("from index-routes " +allFightScores);
io.sockets.emit('show scores', allFightScores)
})
}
})
//put a callback on the user_scored_fight data, also emit that data with the average scores;
res.json(scored_fight);
}
else if (data[0].f1 === scored_fight.f1 && data[0].f2 === scored_fight.f2 && data[0].user_email === scored_fight.user_email) {
res.json(200);
console.log("data already judged.");
}
})
}
以下是我在我的客户端上捕获数据的位置(public / javascripts / script.js):
jQuery(function($){
socket = io.connect();
var $group_f1_score = $('#gf1_score');
var $group_f2_score = $('#gf2_score');
socket.on('show scores', function(mongooseData){
console.log("mongooseData from scripts " + mongooseData)
$group_f1_score.empty();
$group_f2_score.empty();
//sum fighter scores for all user submissions
var f1_sumScore = 0;
var f2_sumScore = 0;
for (var i = 0; i < mongooseData.length; i++){
f1_sumScore += mongooseData[i].f1_score;
f2_sumScore += mongooseData[i].f2_score;
}
//get the simple average
var f1_avgScore = f1_sumScore/mongooseData.length;
var f2_avgScore = f2_sumScore/mongooseData.length;
$group_f1_score.append(f1_avgScore);
$group_f2_score.append(f2_avgScore);
})
})
我不确定为什么数据不会向我的客户端发出,而且我没有想法。我是否正确查询数据并将其传递给回调?
答案 0 :(得分:0)
我无法在您的代码中看到这一点:
server.listen(port);