[英]Gerting error db.collection is not a function?
我在 mongodb 中使用 socket.io 和 nodejs/express。 在 server.js 中,我將數據存儲在 mongodb 中,但出現錯誤 db.collection is not a function 為什么會這樣?
我已經看到這個問題 -> db.collection is not a function when using MongoClient v3.0但我無法理解如何修改我的代碼以便它可以工作? 我應該將所有代碼移到.then()
嗎?
代碼:
服務器.js:
const express = require('express');
const mongoose = require('mongoose');
const socket = require('socket.io');
const message = require('./model/message')
const app = express();
const db = require('./config/keys').mongoURI;
mongoose.connect(db, {useNewUrlParser: true})
.then(() => console.log('Mongodb connected...'))
.catch( err => console.log(err));
const port = 5000;
let server = app.listen(5000, function(){
console.log('server is running on port 5000')
});
let io = socket(server);
io.on("connection", function(socket){
console.log("Socket Connection Established with ID :"+ socket.id)
socket.on('disconnect', function(){
console.log('User Disconnected');
});
let chat = db.collection('chat'); <---GETTING ERROR HERE
socket.on('SEND_MESSAGE', function(data){
let message = data.message;
let date = data.date;
// Check for name and message
if(name !== '' || date !== ''){
// Insert message
chat.insert({message: message, date:date}, function(){
socket.emit('output', [data]);
});
}
});
chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
if(err){
throw err;
}
// Emit the messages
socket.emit('RECEIVE_MESSAGE', res);
});
})
注意:我的 mongo 版本是 4
您需要將連接傳遞給 db 對象,如下所示
const mongoURI = require('./config/keys').mongoURI;
mongoose.connect(mongoURI, {useNewUrlParser: true}
db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('Mongodb connected...')
});
在此之后,您就可以使用db
對象了。 然后創建schmea
和models
並使用它來插入或查詢數據。 在你的情況下,它是一個chat
模型。
看來你對mongoose
用法不太清楚,所以我建議你先閱讀文檔: https : //mongoosejs.com/docs/index.html
嘗試一下
const url = "mongodb://<dbuser>:<dbpassword>@ds141633.mlab.com:41633/mongochat";
const options = const options = {
useNewUrlParser: true,
autoIndex: false, // Don't build indexes
reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
reconnectInterval: 1000, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0,
connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
family: 4 // Use IPv4, skip trying IPv6
};
// 連接數據庫...
**
mongoose.connect(url, options).then(
() => {
console.log('database connected');
},
err => console.log(err)
);
mongoose.Promise = global.Promise;
**
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.