I am having trouble connecting my server to MongoDb database using mongoose. The server will start and then crash while trying to connect to mongoDB. the error is getting caught in db.js and then exiting the program. It seems the server will connect to local host then end when it trys to connect to mongoDB.
ERROR!
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Server is running on : http://localhost:8000
MongoDB is not connected
[nodemon] app crashed - waiting for file changes before starting...
here Is my db.js I have linked it to my sever.js file
const mongoose = require('mongoose')
const connectDB = async()=>{
try{
await mongoose.connect("mongodb+srv://jj-test:[email protected]/?retryWrites=true&w=majority")
console.log("MongoDB is connected!")
}catch(err){
console.log("MongoDB is not connected")
console.error()
process.exit(1)
}
}
module.exports=connectDB
server.js
const express = require("express");
const cors = require("cors");
const dotenv = require('dotenv');
const mongoose = require('mongoose')
const crypto = require('crypto')
const path = require('path')
const GridFsStorage = require('multer-gridfs-storage')
const multer = require('multer')
const Grid = require('gridfs-stream')
const connectDB= require('./services/db')
const PORT = process.env.PORT || 8000;
const app = express();
const init = async ()=>{
app.use(express.json());
app.use(express.urlencoded({ extended: false }))
app.use(cors());
await connectDB()
const conn = mongoose.connection
const gfs = await Grid(conn.db,mongoose.mongo)
gfs.collection('media')
// storage location using muster
const storage = await new GridFsStorage({
db: conn.db,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename =
buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename,
bucketName: 'media'
};
return resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
// uploading a file route
app.post('/upload',upload.single('file'),(req,res)=>{
res.json(req.file)
})
// media bucket route
app.get('/files',async(req,res)=>{
try{
const files =await gfs.files.find().toArray()
res.json(files)
}catch(err){
res.status(400).send(err)
}
})
// route for streaming a file
app.get('/read/:filename',async(req,res)=>{
const{filename}= req.params
try{
const readstream = await gfs.createReadStream({filename})
readstream.pipe(res)
}catch(err){
res.status(400).send(err)
}
})
app.delete('/delete/:filename',async(req,res)=>{
const{filename}=req.params
try{
await gfs.files.remove({filename})
res.status(200).end()
}catch(err){
res.status(400).send(err)
}
})
}
init()
app.listen(PORT, () => {
console.log(`Server is running on : http://localhost:${PORT}`);
});
2
Answers
You need add database name:
Also worthwhile adding console.log(err) to help give more descriptive error info on the server.js file