I am using socket.io and nodejs/express with mongodb. In server.js I am storing the data in mongodb but I am getting the error db.collection is not a function why so ?
I have seen this question -> db.collection is not a function when using MongoClient v3.0 but I am not able to understand how can I modify my code so that it can work ? Should I move all the code inside .then()
?
Code:
server.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);
});
})
Note: My mongo version is 4