[英]db.collection is not a function (MongoDB 3+)
I'm making a chat application using MongoDB and Socket.io;我正在使用 MongoDB 和 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...);
每次我运行我的服务器node server.js
我都会通过console.log('MongoDB connected...);
but when it gets to db.collection is throws me an error saying that it's not a function.但是当它到达 db.collection 时会抛出一个错误,说它不是一个函数。
If anyone could look over my code and see if I have any mistakes.如果有人可以查看我的代码,看看我是否有任何错误。 Thanks!谢谢!
Server Side (server.js)服务器端 (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)客户端 (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 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": "*"
}
}
I plan on connecting to my server remotely as I plan on later using what I've learned with PhoneGap.我计划远程连接到我的服务器,因为我计划稍后使用我在 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.这是因为当你连接时你没有得到err
和db
对象,你得到了err
和client
对象。
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 .您应该查看 mongodb 文档,尤其是此处的连接示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.