我正在使用MongoDB和Socket.io制作聊天应用程序;但是,我在这个问题上停留了很长时间。每次我运行服务器node server.js
时,我都会通过console.log('MongoDB connected...);
,但是当它进入db.collection时会抛出一个错误,说它不是函数。
如果有人可以查看我的代码,看看我是否有任何错误。谢谢!
服务器端(server.js)
const mongo = require('mongodb').MongoClient;
const client = require('socket.io').listen(4000).sockets;
// connect to mongo
mongo.connect('mongodb://127.0.0.1/uchat', { useNewUrlParser: true }, function(err, db){
if (err) {
throw err;
}
console.log('MongoDB connected...');
// connect to Socket.io
client.on('connection', function(socket){
let chat = db.collection('chats');
// create function to send status
sendStatus = function(s) {
socket.emit('status', s);
}
// get chats from mongo collection
chat.find().limit(100).sort({_id:1}).toArray(function(err, res) {
if (err) {
throw err;
}
// if no err emit the messages
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 message
sendStatus('Please enter a name and message.');
} else {
// insert message
chat.insert({name: name, message: message}, function() {
client.emit('output', [data]);
// send status object
sendStatus({
message: 'Message sent',
clear: true
})
});
}
});
// handle clear messages
socket.on('clear', function(data){
// remove all chats from the collection
chat.remove({}, function(){
// let user know
socket.emit('cleared');
});
});
});
});
客户端(index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<style>
#messages{height:300px;}
</style>
<title>uChat</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 col-sm-12">
<h1 class="text-center">
uChat
<button id="clear" class="btn btn-danger">Clear</button>
</h1>
<div id="status"></div>
<div id="chat">
<input type="text" id="username" class="form-control" placeholder="Enter name...">
<br>
<div class="card">
<div id="messages" class="card-block">
</div>
</div>
<br>
<textarea id="textarea" class="form-control" placeholder="Enter message..."></textarea>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.dev.js"></script>
<script>
(function(){
var element = function(id) {
return document.getElementById(id);
}
// get elements
var status = element('status');
var messages = element('messages');
var textarea = element('textarea');
var username = element('username');
var clear = element('clear');
// set default status
var statusDefault = status.textContent;
var setStatus = function(s) {
// set status
status.textContent = s;
// if status doesn't equal default clear after 4s
if (s !== statusDefault) {
var delay = setTimeout(function(){
setStatus(statusDefault);
}, 4000);
}
}
// connect to Socket.io server
var socket = io.connect('http://127.0.0.1:4000');
// check for connection
if (socket !== undefined) {
console.log('Connected to Socket.io...');
}
})();
</script>
</body>
</html>
package.json文件
{
"name": "uchat",
"version": "1.0.0",
"description": "Simple Chat App",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"author": "Hunter Shaw",
"license": "ISC",
"dependencies": {
"mongodb": "*",
"socket.io": "*"
}
}
我计划以后使用我在PhoneGap上学到的东西远程连接到服务器。
感谢您的帮助!
终端错误
$ node server.js
MongoDB connected...
C:\Users\hunte\Desktop\uChat\server.js:15
let chat = db.collection('chats');
^
TypeError: db.collection is not a function
at Namespace.<anonymous> (C:\Users\hunte\Desktop\uChat\server.js:15:23)
at Namespace.emit (events.js:182:13)
at Namespace.emit (C:\Users\hunte\Desktop\uChat\node_modules\socket.io\lib\namespace.js:213:10)
at C:\Users\hunte\Desktop\uChat\node_modules\socket.io\lib\namespace.js:181:14
at process._tickCallback (internal/process/next_tick.js:61:11)
答案 0 :(得分:1)
这是因为,当您连接时,您不会得到err
和db
对象,而会得到err
和client
对象。
所以基本上您要做的是:
let db = client.db("YOUR_DB_NAME")
let chat = db.collection("chat")
然后它应该工作。
您应该查看mongodb文档,尤其是连接示例here。