Could not connect MongoDB Atlas to my goorm IDE - node.js

I am a beginner here.
I am currently setting up my goorm IDE and trying to connect MongoDB Atlas.
However, I couldn't connect my MongoDB Atlas cluster to my goorm IDE which shows the below message:
ERROR failed to connect to server [cluster0-shard-00-00-1kwgi.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.]
I have tried to whitelist the IP with 0.0.0.0/0 as followed the tutorial of Ian Schoonover. However, I still could not connect my MongoDB Atlas.
Below is my code in IDE
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
mongoose.connect('mongodb+srv://dylanOh:123456#cluster0-1kwgi.mongodb.net/test?retryWrites=true&w=majority',{
useNewUrlParser : true,
useCreateIndex : true
}).then(()=>{
console.log('Connected to DB!');
}).catch(err=>{
console.log('ERROR',err.message);
});
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
//Below is my testing info before setting up the database
const campgrounds =[
{name: 'Shenandoah', image:'https://www.nps.gov/shen/planyourvisit/images/20170712_A7A9022_nl_Campsites_BMCG_960.jpg?maxwidth=1200&maxheight=1200&autorotate=false'},
{name: 'Mount Rainier', image:'https://www.nps.gov/mora/planyourvisit/images/OhanaCampground2016_CMeleedy_01_web.jpeg?maxwidth=1200&maxheight=1200&autorotate=false'},
{name: 'Florida', image:'https://www.visitflorida.com/content/visitflorida/en-us/places-to-stay/campgrounds-florida/_jcr_content/full_width/vf_image.img.1280.500.jpg'}]
app.get('/',(req, res)=>{
res.render('landing');
});
app.get('/campgrounds', (req,res)=>{
res.render('campgrounds', {campgrounds:campgrounds});
});
app.post('/campgrounds', (req,res)=>{
const name=req.body.name ;
const image=req.body.image;
const newCampground = {name:name, image:image}
campgrounds.push(newCampground);
res.redirect('/campgrounds');
});
app.get('/campgrounds/new', (req,res)=>{
res.render('new');
});
app.listen('3000', ()=>{
console.log('YelpCamp has started!');
});
As an expected outcome, it should be showing 'Connected to DB!' at my terminal.
However, 'ERROR failed to connect to server [cluster0-shard-00-00-1kwgi.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.]' was shown.

I suggest you to create a new db user since the error is an authentication error, you might forget your first created db user's password, I sometimes forget it when I first create the user :)

You see “test?” in url ? That must be replaced with the name of collection you try to connect to.

Related

Empty array problem!!!!!! using node.js, mongoose connected to mongodb database

I tried all the solving on the internet and still got an empty array, I use Studio 3T connected it to MongoDB database and I want to use app.get to see my collection's object. I used the Studio 3T terminal and used db.articles.find() where I can see the objects. But on hyper terminal no, I can't get anything and the code is exactly as from most of the people in the course, as I checked everything for the spelling of letters if it's capital or not but all alright nothing seems wrong, so I hope anyone helps me with that. Thank you in advance!!! This is the code below:
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const ejs = require("ejs");
const app = express();
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/wikiDB");
const articleSchema = {
title: String,
content: String
};
const Article = mongoose.model("Article", articleSchema);
app.get("/articles", function(req, res){
Article.find({}, function(err, foundArticles){
res.send(foundArticles);
});
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
And here the terminal of Studio 3T(Robo 3T) looks like this and I can see the objects of my collection:
enter image description here
It will work if you make changes like below.
const articleSchema = new mongoose.Schema({
title: String,
content: String
});

How does mongoose model connect with mongodb?

I have structured a user collection using mongoose.model().This model exist in seperate file called as model\user.js. The mongodb connection instance (using mongoose) exist in seperate file db\mongoose.js. Both of these files are imported into server.js to work with web application.
var express = require('express');
var bodyParser = require('body-parser');
var {mongoose} = require('./db/mongoose');
var {User} = require('./models/user');
var app = express();
app.use(bodyParser.json());
app.post('/todos', (req, res) => {
var user = new User({
text: req.body.text
});
user.save().then((doc) => {
res.send(doc);
}, (e) => {
res.status(400).send(e);
});
});
app.listen(3000, () => {
console.log('Started on port 3000');
});
module.exports = {app};
The {mongoose} and {User} seems to be a separate entities and model\user.js didn't import ./db/mongoose.js as well . The user model being static content , how does user.save() connects with db and save the document?
First of all let me tell you what is happening in your project.
in Mongoose file:
You have DB connection with Mongoose.
Now Mongoose has your DB connection.
That is the reason it is imported in server.js file.
Secondly, in you model/user.js you have
Declared Schema using Mongoose.
user.save method.
When you use Mongoose here (or any DB related query), it points to your connected DB. Which does not require any explicit connection written in some file.
For more details read Mongoose Docs.
Hope I cleared your thoughts.

Queries with MongoDB in Production (Authentication) not working

I am writing a very simple application with NodeJS and Mongoose.
If I disable authentication in Mongoose, everything works fine and I can access my records from the database. But when I turn on the authentication and configure my NodeJS code to use authenticated Mongoose connection it doesn't let me query my records and the web page keeps on loading.
Name of my database is "bears".
P.S. I have created my users in "Admin database and Bears" database. I have given a user of books database readwrite permissions and it works fine when I authenticate it through "Mongo" command or db.auth command. But it is not working through NodeJS/Mongoose.
Here is my code.
var mongoose = require('mongoose');
var opt = {
user: 'bearsdev',
pass: 'bearsdev123!',
auth: {
authdb: 'bears'
}
};
mongoose.connect('mongodb://localhost:27017/bearsdev',opt);
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
In my server.js
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var Bear = require('../models/bear');
var bear = require('express').Router();
bear.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
bear.get('/bear',function(req, res) {
Bear.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
app.use('/test', bear);
app.listen(8080);
localhost:8080/test works.
localhost:8080/test/bear keeps on loading.
I have tried different ways of authentication with Mongoose, e.g.
mongoose.connect('mongodb://bearsdev:bearsdev123!#localhost:27017?authSource=bearsdev');
and
mongoose.connect('mongodb://bearsdev:bearsdev123!#localhost:27017/bearsdev');
None of these ways are working for me.
I hope following code may be work.
database = {
host: 'localhost',
db: 'bears',
port: '27017',
options: {
user: "bearsdev",
pass: "bearsdev123!",
auth: {
authdb: 'admin'
}
}
}
mongoose.connect(database.host, database.db, database.port, database.options, function (err) {
if (err) {
console.log("connection error:", err);
} else {
console.log("MongoDB connection successful");
}
});
I was able to solve the problem by uninstalling local node module of Mongoose and then installing the latest version. Probably some intermediate version (~3.6.13) had that bug. But latest Mongoose is good to go.

Fail to retrieve data from MongoDb on Node.Js API

I have a MongoDb server hosted on Azure. I'm now building a Node.js API meant to retrieve data from a table on one of the databases (i.e. table: Word; database: MyDatabase). I've built the API following this tutorial, but I'm unable to successfully retrieve any data from it...
I know the server is up and running and also reachable since I can tcp-connect to it through:
psping [Azure's Public IP]:27017
Now, I have an node.js api with the following code:
1) app/server.js
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://[Azure's public IP]:27017/MyDatabase');
var Word = require('./models/word');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR API
var router = express.Router(); // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next();
});
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
router.route('/words')
.get(function(req, res) {
Word.find(function(err, words) {
if (err)
res.send(err);
res.json(words);
});
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
I've also written a model for my only table within the database, which has 3 columns: the auto-generated ObjectId, Spanish, French (meant to have words in both languages to make it work as a translator). The models looks like this: 2) app/models/word.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var WordSchema = new Schema({
spanish: String,
french: String
})
var Word = mongoose.model('Word',WordSchema);
module.exports = Word;
Now, I go to postman and GET on the following: http://localhost:8080/api/words; which returns [].
On MongoDb logs I see the following:
2016-08-05T03:16:26.520+0000 I NETWORK [conn60] end connection [Some IP]:[Some port] (1 connections now open)
2016-08-05T03:31:11.878+0000 I NETWORK [initandlisten] connection accepted from [Some IP]:[Some port] #61 (1 connection now open)
As you mentioned in your comment that the documents were retrieved from db.word.find() I think I found the problem. You need to put documents into collection named words, instead of word.
Mongoose will use the plural version of your model name. See http://mongoosejs.com/docs/models.html for more information.
I think you are missing {} when doing find.
router.route('/words')
.get(function(req, res) {
Word.find({}, //Added here.
function(err, words) {
if (err)
res.send(err);
console.log(words)
res.json(words);
});
});
Hope this will help.
EDIT:-
According the document of doc, the find function accept the first parameter as an object and treat it as conditions, but not a callback function.

cant connect to Local mongodb server with nodejs

when trying to connect to mongo db from the project directory i get this
/Users/tadeothompson/Documents/design work/stressful/site/node_modules/connect-mongo/lib/connect-mongo.js:133
throw err;
^
MongoError: cannot connect to server
at Collection.listIndexes (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1712:11)
at indexInformation (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:1531:25)
at Db.indexInformation (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:1498:44)
at ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:1003:8)
at Db.ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:982:44)
at ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1772:13)
at Collection.ensureIndex (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/collection.js:1760:44)
at connectionReady (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/connect-mongo/lib/connect-mongo.js:141:27)
at Db.collection (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/mongoose/node_modules/mongodb/lib/db.js:425:20)
at initWithNativeDb (/Users/tadeothompson/Documents/design work/stressful/site/node_modules/connect-mongo/lib/connect-mongo.js:207:20)
at process._tickCallback (node.js:355:11)
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3
managed to connect using a simple app (code below)
*
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log("We are connected");
}
});
*
the main node file of the app in question code is below:
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var mongoStore = require('connect-mongo')({session: expressSession});
var mongoose = require('mongoose');
require('./models/users_model.js');
var conn = mongoose.connect('mongodb://localhost:27017/stressfullproject');
var app = express();
app.engine('html', require('ejs')._express);
app.set('views', './site' + '/views');
app.set('view engine', 'html');
app.use(bodyParser());
app.use(cookieParser());
app.use(expressSession({
secret: 'stress',
cookie: {maxAge: 60*60*1000},
store: new mongoStore({
db: mongoose.connection.db,
collection: 'sessions'
})
}));
require('./routes/routes')(app);
app.listen(80);
*
my defined schema
*var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var UserSchema = new Schema({
username: { type: String, unique: true },
email: String,
hashed_password: String
})
mongoose.model('User', UserSchema)*
because i can connect with the other app, im thinking its an issue with one of my modules? ive searched all over.
thanks in advance
My best guess is that you are using two modules namely MongoClient and mongoose both are trying to connect to port 27017. Now in this race only one will win and will lock that port. If you try and bind to that port it will give you an error, similar to the one you are getting above. My suggestion, don't use MongoClient. use only mongoose. There is a lot of help available for mongoose and many video tutorials on youtube use it.
If that doesn't help let me know.
Let's prep you up with some code shall we. I don't use MongoClient now, but when I used to I wrote this code, see of it works. If it doesn't please paste the stacktrace.
var MongoClient=require('mongodb').MongoClient,
server=require('mongodb').Server;
var mongoclient=new MongoClient(new server('localhost',27017));
mongoclient.connect('mongodb://localhost:27017/course',function(err,db)
{
if(err) throw err;
//var db=mongoclient.db('course');
var query={'grade':100};
db.collection('grades').findOne(query,function(err,doc)
{
if(err) throw err;
console.dir(doc);
db.close();
});
});
i found the answer in another stack overflow post here
the problem was that the session (or something else outside of mongoose) was trying to connect to the database BEFORE mongoose established a connection.
Either one of two issues - either you are calling an undefined schema (mongoose) or you have a function requiring next but next is undefined. I've run into this problem many times and it's documented lack of error handling with mongoose. You need to define some error handling early in your app.js file.
Mongodb version v4.2.6 ---
Node.js version: v14.2.0
first, make sure you are running mongodb local server, check for exsiting db by bellow command:
show dbs
output:
Now I want to connect with database tours-test
first install mongooes by command
npm i mongoose
Now in you connection.js
const mongoose = require('mongoose');
const conStr = 'mongodb://localhost:27017/tours-test';
mongoose
.connect(conStr, {
usedNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then((con) => console.log('DB connection successful'));
// remember mongoose.connect() return Promise

Resources