I'm making a chat application using MongoDB and Socket.io; however, I've been stuck on this problem for quite awhile. every time I run my server node server.js
I get passed the console.log('MongoDB connected...);
but when it gets to db.collection is throws me an error saying that it's not a function.
If anyone could look over my code and see if I have any mistakes. Thanks!
Server Side (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');
});
});
});
});
Client Side (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 file
{
"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": "*"
}
}
I plan on connecting to my server remotely as I plan on later using what I've learned with PhoneGap.
Thanks for the help!
Terminal Error
$ 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)
It's, because when you connect you don't get the err
and db
object you get the err
and client
object.
so basically what you have to do is:
let db = client.db("YOUR_DB_NAME")
let chat = db.collection("chat")
and then it should work.
You should look at the mongodb docs, especially the connect example here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.