2017-12-25 35 views
0

私は、mongoDBとnodejを使って簡単なチャットアプリケーションを作成するためのチュートリアルをフォローしています。動画のコメントは見栄えが良く、この問題に直面しているようです。下のコードを参考にしてください。mongoDBとnodejsを使用してエラーを生成しているスクリプト--db.collectionは関数ではありませんか?

//create a variable mongo and require the mongodb module here 
const mongo=require('mongodb').MongoClient; 

//create a variable called client,require socket and listen to particular port 
const client=require('socket.io').listen(4000).sockets; 

//connect to mongodb 
mongo.connect('mongodb://127.0.0.1/mongochat',function(err,db){ 
    if(err) throw err; 
    console.log('MongoDB connected...'); 

    //start to work with socket.io 

    //1.connect to socket.io 
    client.on('connection',function(socket){ 
     let chat=db.collection('chats'); 

     //create function to send status to the client 

     sendStatus =function(s){ 
      socket.emit('status',s); 
     } 
      //get chats from the mongo collections 
      chat.find().limit(100).sort({__id:1}).toArray(function(err,res){ 
      //check for errors 
      if(err) throw err; 
      //else emit 
      socket.emit('output',res); 

      }); 
      //handle input events 
      socket.on('input',function(data){ 
      let name=data.name; 
      let message=data.message; 

      //check for name and message 
      if(name==' '||message==' '){ 
       //send error status 
       sendStatus('please enter name and message'); 
      }else 
      { 
       //insert message 
       chat.insert({name: name,message: message},function(){ 
        client.emit('output',[data]); 

        //send status objects 
        sendStatus({ 
        message:'Message sent', 
        clear:true 

       }); 

       }); 
      } 
      }); 
      //handle clear 
      socket.on('clear',function(data){ 
      //remove all chats from the collections 
      chat.remove({},function(){ 
       //emit cleared 
       socket.emit('cleared'); 
      }) 
      }) 



    }) 
}) 

エラーを出すdb.collectionは関数ではありません。 私はsocket.ioの初心者です。だから私は正確にエラーが発生する理由を見つけることができませんでした。 注:私は32ビットWindowsマシン上でmongoDBを実行しています(インストールには苦労しましたが、スタックオーバーフローの助けを借りて完了しました)。 私はチュートリアルのコードで2回、さらに3回チェックしました。しかし、修正できませんでした。このエラーで私を助けてください。

答えて

0

mongodbノードドライバのバージョン3.0を使用している可能性があります。それは新しいバージョンであり、多くのチュートリアルは少し古くなっています。 npm list mongodbを使用して、ドライバのバージョンを確認することができます。 3.0では、MongoClient.connect()は、そのコールバックへのクライアント・オブジェクトを渡し

mongo.connect('mongodb://127.0.0.1/mongochat', function(err, db){ 
    chat = db.collection('chats') 
} 

は、古いバージョンでは、これはコードでした。だから今:それはだ:

mongo.connect('mongodb://127.0.0.1/mongochat', function(err, client){ 
    chat = client.db.collection('chats') 
} 

3.0 hereの変更ログを参照してください。

もちろん、socket.ioクライアントの名前はclientなので、それらの変数のうちの1つに別の名前を使用して衝突しないようにする必要があります。

+0

ありがとうございます。package.jsonファイルで古いバージョンに変更しようとしましたが、再インストールしました。これは私のために働いています。ご協力いただきありがとうございます。 – Mariappan

+0

問題ありません!それが助けてくれてうれしい。 – tfogo

関連する問題