Terminal
[nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
(node:16036) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)
server is running on 5000
db error
this is index.js
const express = require('express');
const app = express();
var mongoUrl ="mongodb://localhost:27017/TestDB"
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/TestDB", { useNewUrlParser: true, useUnifiedTopology: true }, (err) => {
if (!err) console.log('db connected');
else console.log('db error');
})
app.listen(5000, () => {
console.log('server is running on 5000');
});
mongoose
.connect(`mongodb+srv://DB_USER:DB_PASS#cluster0.mbv6h.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('Database connection successful!');
}).catch(error){
console.log(error)
}
you can get the entire connection string from MongoDB and input your DB user and password
It seems that you are trying to connect to a local instance of MongoDB. I remember this caused me a few headaches.
Try making sure that you have it downloaded and running:
Open command prompt (on Windows) or terminal (on MacOS)
Type mongod and click enter
If you get a long response then you have it installed but it might not be running or running on the correct port.
If you get a response something like this: 'mongod' is not recognized as an internal or external command, operable program or batch file. then that means you don't have MongoDB installed https://www.mongodb.com/docs/manual/administration/install-community/ to find instructions on how to install it.
Also...
The code you are using would work but it's a little untidy.
Try:
const express = require("express")
const mongoose = require("mongoose")
const app = express()
// Define port and mongodb url once so you don't have to repeat yourself
const PORT = 3000
const MONGO = "mongodb://localhost:27017/TestDB"
// Add this line to get rid of the first error you got
mongoose.set("strictQuery", false)
mongoose
.connect(MONGO, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("Database connected!"))
.catch((err) => console.log(err))
app.listen(PORT, () => {
console.log("Server is running on port " + PORT)
})
Related
I'm trying to clone whatsapp.. I've done with frontend part.. but when I try to connect with mongodb and get & post a request through postman api... but my code is getting crashed.
I'm using "type":"module" in package.json
This is what i'm getting in terminal
Listening on localhost:9000
D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongodb\lib\connection_string.js:282
throw new error_1.MongoParseError(`${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported`);
^
MongoParseError: option usecreateindex is not supported
at parseOptions (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongodb\lib\connection_string.js:282:15)
at new MongoClient (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongodb\lib\mongo_client.js:45:63)
at D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\connection.js:802:16
at new Promise (<anonymous>)
at Connection.openUri (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\connection.js:799:19)
at D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\index.js:409:10
at D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\index.js:1262:10) {
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.13.0
[nodemon] app crashed - waiting for file changes before starting...
import express from 'express';
import mongoose from 'mongoose';
import Messages from './dbMessages.js';
const app = express();
const port = process.env.PORT || 9000;
app.use(express.json());
const connection_url = 'mongodb+srv://sarath_babayaga:Sarath#1996#cluster0.wzoouq0.mongodb.net/clone-whatsapp-backend? retryWrites=true&w=majority'
mongoose.connect(connection_url,{
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
})
app.get('/',(req,res)=>res.status(200).send('hello world!!!!'));
app.get('/messages/sync', (req, res) => {
const dbMessage = req.body
Messages.find ((err, data) => {
if (err) {
res.status(500).send(err)
} else {
res.status(200).send(data)
}
})
})
app.post('/messages/new', (req, res) => {
const dbMessage = req.body
Messages.create(dbMessage, (err, data) => {
if (err) {
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.listen(port,()=>console.log(`Listening on localhost:${port}`));
according to the official forum of MongoDB, UseCreateIndex is deprecated since Mongoose 6, so I think this is the issue. Try removing useCreateIndex from your code
https://www.mongodb.com/community/forums/t/option-usecreateindex-is-not-supported/123048/3
I have completed a project and trying to deploy on heroku. I am using Reactjs frontend and express Nodejs with mongoose and mongodb in the Backend. It works on localhost but when I run Build it and try to deploy it on heroku it gives an application error.
Here is my backend connection code:
require('dotenv').config();
const express = require('express')
const session = require("express-session")
const bodyParser = require('body-parser')
const cors = require('cors')
const zomatoRoutes = require('./Routes/zomato')
const paymentRoutes = require('./Routes/payments')
const mongoose = require('mongoose')
const passport = require("passport")
const MongoStore = require('connect-mongo');
const uri = process.env.MONGO_URI || 'mongodb://localhost/zomato';
console.log(uri,'this is the mongo Atlas uri if connected using that !!!')
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName:'zomato1'
}
const connectDB = async () => {
await mongoose.connect(uri, options ).then(() => {
console.log('mongo connected')
}).catch( e => console.log(e))
}
connectDB().then(() => {
app.listen( process.env.PORT ||5252 , () => {
console.log("express app is up and running on port 5252");
})
})
I also have mongo session store the mongoose session when user logs in
app.use(session({
secret: "this is unambigous secret",
resave: false,
saveUninitialized: false,
cookie: { maxAge: 24*60*60*1000 },
store : MongoStore.create({
client: mongoose.connection.getClient(),
dbName:'zomato1',
ttl: 14 * 24 * 60 * 60
})
}));
app.use(passport.initialize());
app.use(passport.session());
It gives me MongoNotConnectedError: MongoClient must be connected to perform this operation error when I try to deploy using
git push heroku master:main
full error tail :
mongodb+srv://vishal_torne_22:********#db-first-hernode.zu6btrs.mongodb.net/<DBNamecomeshere>?retryWrites=true&w=majority this is the mongo Atlas uri if connected using that !!!
2022-07-31T11:19:34.581869+00:00 app[web.1]: /app/node_modules/mongodb/lib/utils.js:367
2022-07-31T11:19:34.581876+00:00 app[web.1]: throw new error_1.MongoNotConnectedError('MongoClient must be connected to perform this operation');
2022-07-31T11:19:34.581877+00:00 app[web.1]: ^
2022-07-31T11:19:34.581877+00:00 app[web.1]:
2022-07-31T11:19:34.581878+00:00 app[web.1]: MongoNotConnectedError: MongoClient must be connected to perform this operation
2022-07-31T11:19:34.581878+00:00 app[web.1]: at getTopology (/app/node_modules/mongodb/lib/utils.js:367:11)
2022-07-31T11:19:34.581881+00:00 app[web.1]: at Collection.createIndex (/app/node_modules/mongodb/lib/collection.js:258:82)
2022-07-31T11:19:34.581881+00:00 app[web.1]: at MongoStore.setAutoRemove (/app/node_modules/connect-mongo/build/main/lib/MongoStore.js:147:35)
2022-07-31T11:19:34.581881+00:00 app[web.1]: at /app/node_modules/connect-mongo/build/main/lib/MongoStore.js:128:24
2022-07-31T11:19:34.581882+00:00 app[web.1]: at processTicksAndRejections (node:internal/process/task_queues:96:5)
2022-07-31T11:19:34.581882+00:00 app[web.1]:
2022-07-31T11:19:34.581882+00:00 app[web.1]: Node.js v17.9.1
2022-07-31T11:19:34.703486+00:00 heroku[web.1]: Process exited with status 1
2022-07-31T11:19:34.791551+00:00 heroku[web.1]: State changed from starting to crashed
I am using Mongoose to connect the Mongodb, It works on localhost without heroku but when I deploy it using heroku, It asks me to use MongoClient. Is it a requirement to use mongoClient on Heroku 20 stack, I also get warning to upgrade to new Heroku version, I tried to upgrade heroku using npm upgrade heroku to the specifed version it shows successful but again rolls back to heroku 20 stack.
here's what I tried but researching the previous answers :
I added on my mongodb atlas the whitelist 0.0.0.0/0 (includes you current IP address)
I tried to make the mongoose code async so that it connect firsts the database then app listens to the port.
changed the engine version so that it supports latest node and npm version on Heroku like:
{
"version": "1.0.0",
"engines": {
"node": "17.x",
"npm":"8.x"
}
}
Is it a requirement to use MongoClient on heroku 20 stack ? as the Error shows... and why it is showing error on Mongoose.connect()
Thanks in advance..!
As you say it runs fine in your local environment, the issue may be fixed by adding process.env.MONGO_URL to the config vars of your application, as the issue may originate when Heroku tries to connect to your MongoDB, but does not achieve this connection due to an invalid url that is stored in an env variable on your local device.
Hi I am trying to connect MongoDB and I got an error. I worked on connecting DB by "connect with the MongoDB shell", but this time I want to connect with the "connect your application" option.
When I hit mongosh in the embedded terminal in my mac, below was returned.
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.2.2
Using MongoDB: 5.0.6
Using Mongosh: 1.2.2
...
...
...
test>
Because I am new to MongoDB, I don't even know if it's correctly working or not. Also, I wanna connect by coding. That's why I am asking here. Below are some parts of my code in an app I have been working on.
Thanks for your time for dedication here. So appreciate it.
// this is db.js file in a config folder.
const mongoose = require('mongoose')
// It must be a promise function to connect db
const connectDB = async () => {
try {
console.log(`try`)
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: 'expense2'
});
console.log(`MongoDB Connected: ${conn.connection.host}`.syan.underline.bold)
} catch (error) {
console.log(`Error: ${error.message}`.red)
process.exit(1);
}
}
module.exports = connectDB;
/*
Here is the error happened
Error: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
[nodemon] app crashed - waiting for file changes before starting...
*/
config.env in the config folder as well.
NODE_ENV = development;
PORT=5000
MONGO_URI=mongodb+srv://mongo:mongo#cluster0.8tjjn.mongodb.net/expense2?retryWrites=true&w=majority
// server.js file
const express = require('express');
const dotenv = require('dotenv');
const colors = require('colors');
const morgan = require('colors');
const connectDB = require('./config/db')
dotenv.config({ path: "./config/config.env" })
connectDB();
const app = express();
const transactionsRouter = require('./routes/transactions')
app.use('/transactions', transactionsRouter)
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
I am trying to connect to cloud mongo db using mongoose with the connection string
const mongoose = require("mongoose");
mongoose.connect(
"mongodb+srv://<user>:<pass>#<cluster>/<db>?retryWrites=true&w=majority", {
useNewUrlParser: true,
useUnifiedTopology: true
}
).then(res => {
console.log("successful" + res);
})
.catch(err => {
console.log("connection error:", err);
})
module.exports = mongoose;
This works fine on my local machine but when I upload and run it on my production server it doesn't connect.
I have to set it to allow connections from all IPs and I have also add my server IP to it but still it shows me the same error
trying to connect mongoose to my express app and getting this error:
[nodemon] starting `node index.js`
Listening to the port 5000
connect ECONNREFUSED 35.156.235.216:27017
Im connecting the app directly to MongoDB Atlas, everything was working fine yesterday but this morning i got this Error. Here is the db connection file:
const mongoose = require("mongoose");
require("dotenv").config();
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});
console.log("connected to MongoDB..");
} catch (err) {
console.log(err.message);
}
};