Reputation: 1727
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
Upvotes: 1
Views: 486
Reputation: 128
try it
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
};
// connection with database...
**
mongoose.connect(url, options).then(
() => {
console.log('database connected');
},
err => console.log(err)
);
mongoose.Promise = global.Promise;
**
Upvotes: 0
Reputation: 1441
You need to pass connection to db object like follows
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...')
});
After this you are ready to use db
object. You then create schmea
and models
and use it to insert or query the data. In your case it's a chat
model.
It seems you are not clear with mongoose
usage, so I recommend you to read documentation first: https://mongoosejs.com/docs/index.html
Upvotes: 1