In local mongodb is running when i connect to mongodb atlas it is not connecting and there is no errors.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://NaveenS:naveen#frozenexpression-
jiptd.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, {useNewUrlParser: true,
useUnifiedTopology: true} );
client.connect(err => {
const collection = client.db("yelp_camp").collection("campgrounds");
client.close();
});
In uri your database name is test and you trying to connect 'yelp_camp' so write both same and try again.
Related
I am using Youtube tutorial about API using MongoDB and mongoose. However,I am keep getting this error whenever I do POST something on Postman.
"MongooseError: Operation products.insertOne() buffering timed out after 10000ms"
const { MongoClient } = require('mongodb');
const uri = "mongodb+srv://dusdn1102:" + process.env.MONGO_PW + "#node-rest-shop.wvxmj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
client.close();
});
I am using visual studio code 1.57.1 and the version of MongoDB is 4.4.10.
Please can someone help me??
This will help you.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test')
.then(()=>console.log("DB Connected"))
.catch((err)=>console.log(err))
if you're using the mongoose model use this connection setting or as mentioned in mongoose website
You need to use mongoose to create a connection with the MongoDB. Add the following code to your app.js or server.js first.
const mongoose = require("mongoose");
const uri = "mongodb+srv://dusdn1102:" + process.env.MONGO_PW + "#node-rest-shop.wvxmj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));
db.once("open", function () {
console.log("Connected successfully");
});
Use this to open a connection and then proceed with the insert operation.
I am unable to connect to mongodb from node.js using mongoose as database driver. Also I am getting the following error.
Error:
Error in DB connection:{"ok":0,"code":18,"codeName":"AuthenticationFailed","name":"MongoError"}
I am explaining my code below.
const mongoose = require('mongoose');
const dbUser = process.env.USERNAME || 'admin';
const dbPass = process.env.PASSWORD || 'admin';
const dbServer = 'edqart-mongodb';
const dbPort = process.env.MONGO_PORT || '27017';
let dbName = 'edqart-db';
const url = `mongodb://${dbUser}:${dbPass}#${dbServer}:${dbPort}/${dbName}`;
console.log('url', url);
const options = {
useNewUrlParser: true,
useCreateIndex: true,
connectTimeoutMS: 5000000,
poolSize: 10000,
useUnifiedTopology: true
};
/*
1- Connect to mongo server
*/
mongoose.connect(url, options, (err) => {
if(!err) {
console.log('Mongodb connection with mongoose successed');
} else {
console.log('Error in DB connection:' + JSON.stringify(err, undefined, true));
}
})
Here the database edqart-db is not actually present inside that particular mongo server. I need once one record will insert the db will created dynamically. If I have let dbName = 'admin'; then my node is connected to mongodb but for other db which is not created from beginning its showing error. I need once one record is going to insert then the db edqart-db will created. Here I just need the similar method like client.db(dbName) of require('mongodb').MongoClient for mongoose also.
I don't think its possible to authenticate on non existing db.
Here is what you should do if you want to enable auth on edqart-db.
Create a database edqart-db.
Create a user on that edqart-db. lets say username=edqartReadUser and password=edqartReasPassword.
Then your existing code should work below url.
const dbUser = process.env.USERNAME || 'edqartReadUser';
const dbPass = process.env.PASSWORD || 'edqartReasPassword';
const dbServer = 'edqart-mongodb';
const dbPort = process.env.MONGO_PORT || '27017';
let dbName = 'edqart-db';
const url = `mongodb://${dbUser}:${dbPass}#${dbServer}:${dbPort}/${dbName}`;
My nodejs app can't connect to MondoDB Server.
I have already allowed all ip addresses (0.0.0.0/0) to connect.
const mongoose = require('mongoose');
const URL = '' //database url
mongoose.connect(URL, {useNewUrlParser: true}).then(db => {
console.log("Connected")
}).catch(err => {
console.log(err)
})
Above code throws "MongooseServerSelectionError: connection timed out" error
U have to provide URL in mongoose something like this
const url = 'mongodb://localhost:27017/myapp'
But before that please verify whether the mongo is running in your system or not.
Although I am not the first on Stackoverflow not to be able to connect to mongoDB atlas using mongoose, no one seems to have my specific error:
{ MongoNetworkError: failed to connect to server
[cluster0-shard-00-00-shqnc.mongodb.net:27017] on first connect
[MongoNetworkError: connection 5 to
cluster0-shard-00-00-shqnc.mongodb.net:27017 closed]
Here's how my server is set-up:
Keys.js
module.exports = {
mongoURI:
"mongodb+srv://Ahmed:<MyMongoDBAtlasPWD>#cluster0-shqnc.mongodb.net/test?retryWrites=true&w=majority"
};
Server.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(db, {
useNewUrlParser: true
})
.then(() => {
console.log("MongoDB connected!");
})
.catch(err => {
console.log(err);
});
app.get("/", (req, res) => {
res.send("Hello");
});
//process.env.Port is for Heroku
const port = process.env.Port || 5000;
// `` ES6 Template literal is used so that we can put a variable inside the String
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
And this is the code suggested by the MongoDB atlas website to be used:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://Ahmed:<password>#cluster0-shqnc.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
But, since I don't want to use mongoClient but rather mongoose, I am having some trouble and I cannot see why the code doesn't work;
EDIT 1: I have managed to connect using the Shell command(Check-out my answer). However, connecting through the app doesn't work and gives a different error:
{ MongoNetworkError: failed to connect to server
[cluster0-shard-00-01-shqnc.mongodb.net:27017] on first connect
[MongoError: bad auth Authentication failed.]
EDIT 2: I made a stupid mistake. I've forgotten to remove <> from the . All is good now.
The problem is that I was trying to connect using my MongoDB Atlas account password instead of the user password. Yes, those are 2 different things.
1. Click on Database Access
2. Edit the current user and modify the password
3. Use that password to connect to MongoDB Atlas
Make sure you have whitelisted your public IP. You can find that by googling "what is my ip".
I'm using mongoose. 5.8.2 and following a tutorial where the person is running mongoose on v3.5. I know there has been changes like useNewUrlParser has been deprecated and instead we use useUnifiedTopology but the problem is that whenever I use useUnifiedTopology then I get the error that it has been deprecated. Please have a look below and let me know what am I doing wrong
const mongoose = require('mongoose')
mongoose.createConnection('mongodb://127.0.0.1:27017/task-manager-api', {
useUnifiedToplogy: true,
useCreateIndex: true
});
const User = mongoose.model('User', {
name: {
type: String
},
age: {
type: Number
}
})
const me = new User({
name: 'Lallan',
age: '27'
})
me.save().then(() => {
console.log('Done')
}).catch((error) => {
console.log('error', error)
})
and the following is the error and I'm not able to connect mongoose with mongodb
the options [useUnifiedToplogy] is not supported
(node:6573) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:6573) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
What should I do to connect mongoose with mongodb?
The most default connection will be to just { useNewUrlParser: true }. You can use createConnection()(for multiple pools) as well as connect()(single pool).
From MDN a basic example will be:
//Import the mongoose module
var mongoose = require('mongoose');
//Set up default mongoose connection
var mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB, { useNewUrlParser: true });
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
Also,
If you need to create additional connections you can use
mongoose.createConnection(). This takes the same form of database URI
(with host, database, port, options etc.) as connect() and returns a
Connection object.
like,
const db = mongoose.createConnection('mongodb://user:pass#localhost:port/database', opts);
Maybe try giving it this way,
const mongoose = require('mongoose');
let db_uri = "'mongodb://localhost:27017/mydb"
mongoose.connect(db_uri, {
useNewUrlParser: true,
useUnifiedTopology : true
});
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);