Node.js 我的脚本试图创建一个服务器,mongoDB和nodejs给出错误-db.collection不是一个函数吗?
我正在学习使用mongoDB和nodejs创建一个简单的聊天应用程序的教程。视频中的评论看起来不错,似乎只有我面临这个问题。请帮助我编写下面的代码Node.js 我的脚本试图创建一个服务器,mongoDB和nodejs给出错误-db.collection不是一个函数吗?,node.js,mongodb,socket.io,Node.js,Mongodb,Socket.io,我正在学习使用mongoDB和nodejs创建一个简单的聊天应用程序的教程。视频中的评论看起来不错,似乎只有我面临这个问题。请帮助我编写下面的代码 //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 partic
//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我甚至很难安装它,但在堆栈溢出的帮助下完成了安装。
我已经对教程代码进行了两次甚至三次交叉检查。但我无法修复它。请帮助我解决此错误。您可能正在使用mongodb节点驱动程序的3.0版。这是一个新版本,所以很多教程现在都有点过时了。您可以使用npm列表mongodb检查驱动程序的版本 在旧版本中,代码如下:
mongo.connect('mongodb://127.0.0.1/mongochat', function(err, db){
chat = db.collection('chats')
}
在3.0中,MongoClient.connect将客户端对象传递给其回调。现在是:
mongo.connect('mongodb://127.0.0.1/mongochat', function(err, client){
chat = client.db.collection('chats')
}
请参阅3.0的变更日志
当然,由于您命名了socket.io客户端,因此需要为其中一个变量使用不同的名称,以避免冲突。非常感谢。我尝试在package.json文件中将其更改为旧版本并重新安装。它对我很有效。非常感谢您的帮助。没问题!很高兴这有帮助。