I am trying to connect MongoDB with my signup.js, but it's not connecting. I am unable to find the problem. How can I solve this?
Code of signup.js:
const express = require('express')
const app = express()
require("./db/mydb");
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(4000, () => {
console.log(`App listening on port 4000`)
})
Code of mydb.js:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/mydata",{
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true
}).then(()=>{
console.log("connection successful")
}).catch((e)=>{
console.log("Not connected")
})
Error:
App listening on port 4000
Not connected
If the last log statement is replaced with console.log(e), the output is:
MongoParseError: option usecreateindex is not supported
Here you have a simple example of how to connect MongoDB to Node.js using Express.js and Mongoose on localhost obviously:
File server.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("Express and Mongoose connection!");
});
// Connect to db
mongoose
.connect("mongodb://localhost:27017/test")
.then(() => {
// Listen for requests
app.listen(port, () => {
console.log(
`Connected to DB & Server is listening at http://127.0.0.1:${port}`
);
});
})
.catch((error) => {
console.log(error);
});
And as we can read in the Mongoose documentation → no more deprecation warning options
useNewUrlParser, useUnifiedTopology, useFindAndModify, and
useCreateIndex are no longer supported options. Mongoose 6 always
behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex
are true, and useFindAndModify is false. Please remove these options
from your code.
It was tested with: "express": "^4.18.1", "mongoose": "^6.6.5"
Related
I have developed an API endpoint. It was working fine before. Unfortunately the project folder got corrupted (I recreated the files db.js and server.js). But now when I try to fetch data from API, I'm getting:
"connect ECONNREFUSED 127.0.0.1:5005"
The URL I'm using is localhost:
And my server is running on the same port i.e. 5005:
Can someone please elaborate what can be the problem? My hunch is that when I recreated the files I may have missed something:
db.js:
const mongoose = require('mongoose');
const userName = "myUsername"
const password = "myPassword"
const dbName = "comfyRooms"
const dbURL = `mongodb+srv://${userName}:${password}#mongo-cluster.damzf.mongodb.net/${dbName}?authSource=admin&replicaSet=atlas-s7z01e-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true`
mongoose.connect(dbURL, {useUnifiedTopology: true, useNewUrlParser: true})
let connection = mongoose.connection
connection.on('error', () => {
console.log('Unable to connect to MongoDB')
})
connection.on('connected', () => {
console.log("MongoDB connection established :)")
})
module.exports = mongoose
server.js
const express = require('express')
const app = express()
const dbConfig = require('./db')
const roomsRoute = require('./routes/roomsRoute')
app.use('/api/rooms', roomsRoute)
const port = process.env.PORT || 5005
app.listen(() => {
console.log("Node JS server listening on port " + port)
})
roomsRoute.js:
const express = require('express');
const router = express.Router();
const Room = require('../models/rooms');
router.get('/getallrooms', async (req, res) => {
try {
const rooms = await Room.find({});
return res.send(rooms);
} catch (error) {
return res.status(400).json({message: error});
}
});
module.exports = router;
I have attached the important files. Please let me know if any other information is missing. Thanks!
You are not passing the port variable to the listen function, you are just logging it
app.listen(() => {
console.log("Node JS server listening on port " + port)
})
This should work
app.listen(port, () => {
console.log("Node JS server listening on port " + port)
})
Good guys,
I wrote the express API which works perfectly well when tested with POSTMAN but couldn't do same when i try to get a responds displayed on the browser. Would be glad to know where i went wrong from my code base.
Thanks.
My code base below:
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const bdclRoutes = require('./routes/bdcl.routes');
mongoose.connect(process.env.MONGODB_URI, {
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
mongoose.connection.once('open', () => {
console.log('Connected to database successfully....')
}).on('error', () => {<br/>
console.log('Database connection failed.....')
});
const app = express();
app.use(express.json());
app.get('/', (req, res) => {
// res.send('Welcome to BDCL student API')
});
app.use('/api/2020/bdcl_students/uploads', express.static('./uploads'));
app.use('/api/2020', bdclRoutes);
app.listen(process.env.PORT, () => {
console.log(`server started and app running at port ${process.env.PORT}`)
});
the code looks fine. Something might be blocking your port. Change your port number and try again.
I always get "Listening at localhost" but the URL I put is from Mongo Atlas. And when I print the environment variable to the console I get it correctly. mongoose automatically ignores any url other than localhost.
I have tried to restart nodemon muiltiple times.
mongoose
.connect(process.env.DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log(process.env.DATABASE_URL); //prints the correct url but mongoose connects to localhost
console.log("mongo connected");
// logEntry.collection.drop();
})
.catch((error) => console.log(error.message));
validate the connection using the below mentioned code snippet.
const express = require('express');
const app = express();
const socketio = require('socket.io');
const mongoose = require('mongoose');
const expressServer = app.listen(3001);
const io = socketio(expressServer);
mongoose.connect('mongodb+srv://<UserName>:<Password>#democluster0.abcde.mongodb.net?retryWrites=true&w=majority');
mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
mongoose.connection.db.listCollections().toArray(function (err, names) {
console.log(names);
});
})
Refer the below link to gain the URL for the same..
https://docs.atlas.mongodb.com/tutorial/connect-to-your-cluster/
I am writing an app, when I start the server, its working nicely, its connecting to database. But when I start http://localhost:5000 from the browser, it does not respond for a minuite then the browser shows a message:
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
Here is my app.js:
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
app.use(cookieParser);
app.use(express.json());
//const userRouter = require('./routes/user');
//app.use('/user', userRouter);
const startApp = async () => {
try {
await mongoose.connect('mongodb+srv://username:pass#cluster0-dcytp.mongodb.net/test?retryWrites=true&w=majority',
{ useUnifiedTopology: true,useNewUrlParser: true });
console.log(`successfully connected to database`);
const port = process.env.PORT || 5000
app.listen(port, () => {
console.log(`server runnin at ${port}`);
});
} catch (error) {
console.log(error.message)
}
}
startApp();
app.get('/', (req, res) => {
console.log("I am in the root");
res.send("hello World");
})
Why server is not responding from the browser?
try
app.use(cookieParser())
instead of
app.use(cookieParser)
Reference
I had the same problem db is connected but not able to send data. it looks weird but it works for me.
Add a new database user with new password, use the new userName and passw to connect your mongoodb
this is the exact like to add new database user
here is my db connection may it helps you too
mongoose.connect(DATABASE_URL, { useNewUrlParser: true,useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('connected to database'))
app.use(express.json())
I m testing a simple Get api with postman, but i am getting "cannot GET".
server.js (in the root folder)
```const express = require('express');
const mongoose = require('mongoose');
const items = require('./routes/api/items');
const app = express();
//body Parser middleware
app.use(express.json());
//Db config
const db = require('./config/keys').mongoURI;
//const db = "mongodb+srv://gkmm:123123123#cluster0-bo4ln.mongodb.net/test?retryWrites=true&w=majority"
//Connect to mongo
mongoose
.connect(db, { useNewUrlParser:true, useUnifiedTopology: true})
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Server started on port ${port}`));
//Use routes
app.use('./routes/api/items.js', items);```
routes(root folder)/api/items.js
```const express = require('express')
const router = express.Router();
//Item Model
const Item = require('../../models/Item')
//#route GET api/items
//#des Get AAll Items
//access public
router.get('/', (req, res) => {
Item.find()
.sort({ date: -1})
.then(items => res.json(items));
});
module.exports = router; ```
Running into this error while trying to test my API, i checked my paths are correct, my database is connected. but i have no idea why is it returning 404 not found.
After looking through your code, # the line which you ask app to use your routes
//Use routes
/* You are telling the route to go through e.g. <yoururl>/./routes/api/items.js/
in order to reach your GET in items.js
*/
app.use('./routes/api/items.js', items);```
To resolve this issue you can edit your app.use to
app.use('/test', items) // test is just an example, you can change it to other keywords
Then to access your items GET route use "/test/"
Shouldn't app.use('./routes/api/items.js', items); be app.use('/api/items', items); ?