不能打电话的方法'找到'在nodejs中运行时未定义

时间:2015-06-03 04:44:22

标签: javascript node.js mongodb mongojs

我正在使用mongoDB(mongojs)和nodejs。当我运行我的server.js时,我收到以下错误。 TypeError: Cannot call method 'find' of undefined

我不知道为什么会这样。这是我的server.js

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server)

// var mongojs = require('mongojs');
// var db = mongojs('candidates', ['candidates']);

var databaseUrl = "http://localhost:27017/candidates"; 
var db = ('candidates', ['candidates']);
var mongojs = require('mongojs').connect(databaseUrl, db);


var bodyParser = require('body-parser');

app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());

  io.sockets.on("connection", function(socket) {
      console.log('user connected');
      socket.on("disconnect", function(o) {
         console.log('user left');
      });
      socket.emit("connected",{message:'helloworld'});
      socket.on("addVote",function(vote){
         console.log('adding vote');
         console.log(vote);
         io.sockets.emit("addVote",vote);
      })

       socket.on("unVote",function(vote){
         console.log('unvote');
         console.log(vote);
         io.sockets.emit("unVote",vote);
      })

      socket.on("getPrecinct",function(no){
         console.log('getPrecinct');
         console.log(no);
         io.sockets.emit("getPrecinct",no);
      })

      socket.on("nextBallot",function(add){
         console.log('nextBallot');
         console.log(add);
         io.sockets.emit("nextBallot",add);
      })

  })


  app.get('/candidates', function (req, res) {
    console.log('I received a GET request');

    db.candidates.find(function (err, docs) {
      console.log(docs);
      res.json(docs);
    });
  });


  app.put('/updateVotes/:precint_id', function (req, res) {
    var id = req.params.precint_id;
    db.candidates.findAndModify({
      query: {precint_id:id },
      update: {$set: {votes: req.body}},
      new: true}, function (err, doc) {
        console.log(err);
        if(doc == null){
          db.candidates.save({precint_id:id,votes:req.body})
        }
      }
    );
  });

  server.listen(3000);
  console.log("Server running on port 3000");

添加变量databaseUrl时发生错误。我添加它是因为如果我有3台计算机,我希望它们连接到安装了mongodb的1台计算机服务器。为什么我得到Cannot call method 'find' of undefined 的错误。我错过了什么?任何帮助。谢谢

0 个答案:

没有答案