[nodemon] restarting due to changes...
[nodemon] starting node server.js
Server is running on port: ${port}
D:\Practice\mern\mern-exercise\backend\node_modules\mongodb\lib\connection_string.js:290
throw new error_1.MongoParseError(${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported);
^
MongoParseError: option usecreateindex is not supported
at parseOptions (D:\Practice\mern\mern-exercise\backend\node_modules\mongodb\lib\connection_string.js:290:15)
at new MongoClient (D:\Practice\mern\mern-exercise\backend\node_modules\mongodb\lib\mongo_client.js:64:63)
at D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\connection.js:801:16
at new Promise ()
at Connection.openUri (D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\connection.js:798:19)
at D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\index.js:380:10
at D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise ()
at promiseOrCallback (D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (D:\Practice\mern\mern-exercise\backend\node_modules\mongoose\lib\index.js:1225:10) {
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.7.0
[nodemon] app crashed - waiting for file changes before starting...
And the code is
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express ();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true}
);
const connection = mongoose.connection;
connection.once('open', ()=>{
console.log("MongoDB database connection established successfully");
})
app.listen(port, () => {
console.log('Server is running on port: ${port}')
});
process.on('warning', e => console.warn(e.stack));```
According to the mongoose docs
useCreateIndex isn't an option to mongooose.connect()
Related
this is my code
const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser: true, useUnifiedTopology: true}
,(err)=>{
if (err){
console.log(err)
}else {
console.log("Succefully connected")
}
});
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String,
});
const Fruit = mongoose.model("Fruit",fruitSchema)
const fruit = new Fruit({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit"
}
)
fruit.save().then(r => console.log("fruit saved"))
const express = require("express")
const app = express()
app.listen(3000,()=> {
console.log("Server running on port 3000")
});
And this is the error
PS C:\Users\elcha\WebstormProjects\moDB> node app.js
Server running on port 3000
C:\Users\elcha\WebstormProjects\moDB\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:153
const err = new MongooseError(message);
^
MongooseError: Operation `blogs.insertOne()` buffering timed out after 10000ms
at Timeout.<anonymous> (C:\Users\elcha\WebstormProjects\moDB\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:153:23)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)
Node.js v18.12.1
The Mongo db is running and conncted,and when I run in terminal - "node app.js"
I recive the error above
How can I solve this problem (without using Atlas cloud) please...
Having an issue connecting to MongoDB when starting a new MERN stack project:
server.js code:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
.env file:
ATLAS_URI = mongodb+srv://exampleUser:exampleUserPassword#cluster0.y9bpc.mongodb.net/example-
database?retryWrites=true&w=majority
receiving error:
(node:23036) UnhandledPromiseRejectionWarning: MongoError: Authentication failed.
Not sure what I'm doing wrong here, was just following a tutorial. Only difference from the tutorial is the connection string which also requires a dbname which I created and added. I'm hoping it's something more simple than that. I appreciate any help.
So it appears that I chose to add my own IP address instead of allowing access from anywhere and that was the issue. Hooray!
First time using mongoDB. Trying to connect to my cluster that i just created on atlas however i keep getting errors
keys.jss
module.exports = {
mongoURI: 'mongodb+srv://john:<********>#mern-shopping-i5abd.mongodb.net/testretryWrites=true&w=majority'
};
I might be following an outdated tutorial so certain things might be 'unnecessary'
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB config
const db = require('./config/keys').mongoURI;
// Connect to Mongo
mongoose
.connect(db, {useNewUrlParser: true} )
.then(() => console.log('monogoDB Connected...'))
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('Server started on port ${port}'));
Rather than displaying port '5000' i would get an error (different each time)
message: '3rd parameter to mongoose.connect() or mongoose.createConnection() must be a function, got "object"',
name: 'MongooseError'
Here is how it would look with a function as a callback, instead of using promises. Notice that I also moved the app startup inside the callback function. This ensures that the app only starts up when we successfully connect to the DB.
I also moved the DB options (2nd parameter in the connect method), into a variable. This way, it's easy to find and can be modified in one place, if necessary. Ideally, you'd keep all your DB config in a single file, and reference it in other files as needed. Separate concerns :)
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB config
const db = require('./config/keys').mongoURI;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
// Connect to Mongo
mongoose
.connect(db, dbOptions, function(error) {
// we had an error of some kind
if (error) {
console.error(error);
// better yet, we don't want to app to run without our DB!
throw error;
}
// If we made it here, no errors came up
console.log('monogoDB Connected...');
// Start up the app!
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
});
Here is how it would look with the promise structure:
const express = require( "express" );
const mongoose = require( "mongoose" );
const bodyParser = require( "body-parser" );
const app = express();
// Bodyparser Middleware
app.use( bodyParser.json() );
// DB config
const db = require( "./config/keys" ).mongoURI;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
// Connect to Mongo
mongoose
.connect( db, dbOptions )
.then( () => {
console.log( "monogoDB Connected..." );
// Start the application
const port = process.env.PORT || 5000;
app.listen( port, () => {
console.log( `Server started on port ${port}` );
} );
} )
.catch( err => {
console.log( err );
throw err;
} );
I can't connect to the mongoDB, this is the error I'm getting each time:
[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Server started on port 5000
Server selection timed out after 30000 ms
[nodemon] app crashed - waiting for file changes before starting...
Already tried:
- changing ip access on mongoDB from everywhere to current ip adress and otherwise,
- creating new account that was for sure made on my current ip adress,
- disabling firewall,
- checked code for errors,
- tried restarting my pc for some reason
here is my code
//////server.js/////
const express = require('express');
const connectDB = require('./config/db');
const app = express();
// Connect Database
connectDB();
app.get('/', (req, res) =>
res.json({ mgs: 'Welcome to the ContactKeeper API...' })
);
// Define Routes
app.use('/api/users', require('./routes/users'));
app.use('/api/auth', require('./routes/auth'));
app.use('/api/contacts', require('./routes/contacts'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
//////default.json/////
{
"mongoURI": "mongodb+srv://artur123:<artur123>#contactkeeper-lv2py.mongodb.net/test?retryWrites=true&w=majority"
}
//////db.js/////
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = () => {
mongoose
.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB Connected'))
.catch(err => {
console.error(err.message);
process.exit(1);
});
};
module.exports = connectDB;
You just have to add your ip in the ip whitelist on mongoDB Atlas under :
Network Access
then restart.
I am testing my app on localhost and using mongdb to connect to a database. I was receiving this error:
UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:27017
I figured out how to reconnect by going into Services and manually starting MongoDB.
However, after researching, I found that my code is not handling the error catching properly. I am not sure how to restructure my code (using .catch() I believe?) to fix this.
Would appreciate any suggestions to help fix and will be great to be able to learn how to do so.
Thanks in advance!
const express = require('express');
const validate = require('./validate.js');
const mongoose = require('mongoose');
const moviesRouter = require('./routes/movies.js');
const app = express();
const PORT = process.env.PORT || 3000;
const DATABASE_URL = process.env.DATABASE_URL ||
'mongodb://localhost/movies';
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());
app.use('/movies', moviesRouter);
app.listen(PORT, () => console.log(`listening on port: ${PORT}`));
As you suggest, using a catch statement would be one way to handle the connection error:
mongoose.connect(DATABASE_URL, { useNewUrlParser: true,
useUnifiedTopology: true }).catch(error => console.error(error));
If an error happens during connection the error will be handled and returned. More info here: https://mongoosejs.com/docs/connections.html#error-handling