Mongoose schema does not work for Mongo Atlas - node.js

I am migrating the MongoDB database which is running on my local machine to MongoDB Atlas(a copy of the local DB). I have created a middleware using NodeJS and ExpressJS to get the records from the MongoDB.
To access the MongoDB from my Node application, I am making use of Mongoose. I have defined a schema for the collection.
When I am connecting to the local copy of the MongoDB, all the endpoints work correctly and I get the required results. But as soon as I try to access the DB hosted on Atlas, I do not get any results while using mongoose and the same schema. When I try to retrieve the data using mongodb driver and MongoClient, I get the data but not while using mongoose.
Any idea as to why this might be happening? I have checked the permissions of users and it is correctly configured.
Thanks!
index.js:
const url = "mongodb+srv://<username>:<password>#mumbaicluster.4yone.gcp.mongodb.net/<db>?retryWrites=true";
const connect = mongoose.connect(url,{useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true})
var app = express()
app.use(cors())
const connection = mongoose.connection;
connection.once('open',() => {
console.log("Connected!")
app.use("/",productRouter)
})
app.use(bodyParser.urlencoded({extended: true}))
Removed username, password and DB name.
router.js:
productRouter.route("/").get((req, res, next) => {
Product.find({}).then((products) => {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.send(products);
});
});
I can access the DB using MongoDB Compass

Related

Could not connect MongoDB Atlas to my goorm IDE

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.

Mongodb and Express.js: Automatically creating the db and collections based on Models

In Hibernate we can automatically create db and tables (SQL databases) using entity classes. Is it possible to achieve the same facility in Express.js using Mongodb(NoSql).
Just run a local mongodb server and start the application.
When mongoose tries to connect to databse mentioned in the app it creates the database if there is none. Also when you save a document the collections is created automatically
This will create the database on the first run
const mongoose = require('mongoose');
mongoose.connect(process.env.DB_HOST+"/"+process.env.DB_NAME, { useNewUrlParser: true });
This will create the collection for you :
const model = mongoose.model('Model',new mongoose.Schema({
// your schema here
});
var document = new Model({
//your document here
});
document.save((e)=>{
if(e) console.log(e);
// document created in the models collection in database
});

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.

How to connect node API to specific mongoDB db / collection on my local machine

This has probably been asked before because of how high level the question is, however I couldn't find a solution and am struggling to get this set up. I am working on my first full stack web app using MERN stack. I am on a Mac. Everything I'm doing here is on my local machine.
For MongoDB, I have it installed on my local machine. I have the mongod dameom running. Here's what I have in my interactive mongo shell:
// run in terminal
> mongo
> show dbs
admin 0.000GB
config 0.000GB
mydboverhere 0.064GB
local 0.000GB
> use mydboverhere
switched to db mydboverhere
> show collections
table_one
table_two
andathirdtable
I would like to connect my node/express API to the mydboverhere database. In my node directory structure, I have a models directory with:
/models/index.js
var mongoose = require('mongoose');
mongoose.set('debug', true);
// is this line correct?
mongoose.connect('mongodb://localhost:27017/mydboverhere/table_one');
mongoose.Promise = Promise;
module.exports.Todo = require("./table1"); // this requires table1.js
and /models/table1.js
// this matches the form of the data in the database, I believe
var mongoose = require('mongoose');
var tab1Schema = new mongoose.Schema({
name: {
type: String,
required: 'cannot be blank'
},
completed: {
type: Boolean,
default: false
},
created_date: {
type: Date,
default: Date.now
}
})
var Table1 = mongoose.model('Table1', tab1Schema)
module.exports = Table1;
I believe I have my /routes/tableroutes file correct:
var express = require('express');
var router = express.Router();
var db = require('../models')
router.get('/', function(req, res){
// res.send("Hello from the table1 route")
db.Table1.find()
.then(function(data) {
res.json(data);
})
.catch(function(err) {
res.send(err);
})
});
module.exports = router;
and also I think I am loading these routes into my root /index.js file correctly as well:
var express = require('express')
var app = express();
var tableRoutes = require('./routes/tableroutes');
// test the root route
app.get('/', function(req, res){
res.send("Hello from the Root Route")
});
// set base route to /api for my tableRoutes
app.use('/api', tableRoutes);
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Unfortunately, with mongod running, when I try to run node index.js to get my node app running, I receive the following error message in my command line:
... (node:66245) UnhandledPromiseRejectionWarning: Error: Unsupported host 'localhost:27017/mydboverhere/table_one', hosts must be URL encoded and contain at most one unencoded slash ...
And I'm stuck here right now... pretty much, i'm not sure if Im connecting my node API with mongodb correctly or not. This is all being done on my local machine, and I have mongodb installed at /data/db as it should be. Maybe the error is due to the underscore in the collection name table_one. Maybe the error is because the data in the table_one collection in mongo doesnt' match exactly with the schema in table1.js (I created the mongodb separately by pushing a dataframe from R into it, and then wrote the table1.js schema to match it).
Regardless of which of the following above issues is the issue, I'm not sure, and I'm struggling to continue. Any help here is greatly appreciated!
EDIT1: I have a strong feeling that the following line:
mongoose.connect('mongodb://localhost:27017/mydboverhere/table_one');
is incorrect, and am seeing the proper way to connect to a specific db.
EDIT2: I think there's another javascript library called mongoDB for this, but I would very much prefer to get this working with mongoose.
I think there is an error here:
You are using thisdboverhere whereas it should be mydboverhere.
mongoose.connect('mongodb://localhost:27017/mydboverhere', function(){
// do your process here
});
Or
mongoose.connect('mongodb://localhost:27017/mydboverhere');
var db = mongoose.connection // I think you are forgetting to instantiate the connection here
From this good github post here, I found the following:
Make sure you're connecting to the same database
(mongoose.connect('mongodb://hostname:27017/<db name here>'))
and accessing the same collection
(mongoose.model('<model name>', schema, '<collection name here>'))
I'm late to the party, but I had the same error message. Removing the underscore in the database name fixed it for me.
My original database name I tried was:
const URL_MONGODB = "mongodb://localhost:27017/portfolio_db";
I removed the underscore, and used this database name:
const URL_MONGODB = "mongodb://localhost:27017/portfoliodb";
After which, I no longer got the error "UnhandledPromiseRejectionWarning: Error: Unsupported host 'localhost:27017/data/db', hosts must be URL encoded and contain at most one unencoded slash"

Connect multiple mongo db database in node js using mongoose

I am using mongoose for mongo db connections in node js. Can anyone tell me how can I connect multiple databases in node js. Also please make sure that you have tried that method yourself. Thanks.
Edit: I want to connect to multiple DBs dynamically. Also I don't want multiple models and I have just one project, not various sub-projects.
i believe you are connecting to mongoDB from main entrypoint as index.js or server.js , where you are initiating router. like this
`
const mongoose = require('mongoose')
// mongoose
mongoose.connect("mongoDB url");
const connection = mongoose.connection;
connection.on('open',()=>{
console.log(" database connected")
})
connection.on('error',()=>{
console.log("error in connecting to database")
})
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
//middlewares`
in same way you can also connect to different databases directly schemas. like in my use case , i wanted to store users in defferent database and posts in another DB .
the in my app.js , i will connect to main DB as normal connection (above) and for user schema , i will connect to my user DB . like this
const mongoose = require('mongoose');
const connection = mongoose.createConnection("mongo url ");
const userSchema = mongoose.Schema({
name: String,
date_of_birth: Date
})
module.exports = mongoose.model('User', userSchema);
you can also use mongoose.connect() instead of mongoose.createConnection()
hope this helped you.

Resources