私は、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回チェックしました。しかし、修正できませんでした。このエラーで私を助けてください。
ありがとうございます。package.jsonファイルで古いバージョンに変更しようとしましたが、再インストールしました。これは私のために働いています。ご協力いただきありがとうございます。 – Mariappan
問題ありません!それが助けてくれてうれしい。 – tfogo