Hey, I just started learning to code and began with web development. I’m having trouble connecting my Node.js file with my MongoDB database in the terminal. I tried troubleshooting through Stack Overflow, but I wasn’t successful. Please help me out
Hi @Nitin_Gaurav and welcome to the community!
In which database did you create the tweets collection?
From the screenshot you are trying to see if in the test database, the tweets collection ( which does not exist, as we can see from the output of the show collections command) has documents!
I suggest you check to see if that collection has been defined in another database.
Also, I recommend that you take the MongoDB university courses.
Best Regards
“Hey Fabio, thank you for welcoming me. The code below is the main app code that I’m trying to build. I have created the necessary EJS and JS files accordingly. Can you help me figure out how to check the database? I tried troubleshooting using Mongo Atlas documentation, but I’m unable to undo the action, as you can see in the screenshot below. The screenshot that is in the prior question shows the message ‘access control is not enabled for the database,’ and I think that’s the problem.
I’ve already started with MongoDB University courses.”
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const ejsMate = require('ejs-mate');
// const { campgroundSchema, reviewSchema } = require('./schemas.js');
const catchAsync = require('./utils/catchAsync');
const ExpressError = require('./utils/ExpressError');
const methodOverride = require('method-override');
const Campground = require('./models/campground');
const Review = require('./models/review');
mongoose.connect('mongodb://localhost:27017/yelp-camp', {
// useNewUrlParser: true,
// useCreateIndex: true,
// useUnifiedTopology: true
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
const app = express();
app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
const validateCampground = (req, res, next) => {
const { error } = campgroundSchema.validate(req.body);
if (error) {
const msg = error.details.map(el => el.message).join(',')
throw new ExpressError(msg, 400)
} else {
next();
}
}
const validateReview = (req, res, next) => {
const { error } = reviewSchema.validate(req.body);
if (error) {
const msg = error.details.map(el => el.message).join(',')
throw new ExpressError(msg, 400)
} else {
next();
}
}
app.get('/', (req, res) => {
res.render('home')
});
app.get('/campgrounds', catchAsync(async (req, res) => {
const campgrounds = await Campground.find({});
res.render('campgrounds/index', { campgrounds })
}));
app.get('/campgrounds/new', (req, res) => {
res.render('campgrounds/new');
})
app.post('/campgrounds', validateCampground, catchAsync(async (req, res, next) => {
// if (!req.body.campground) throw new ExpressError('Invalid Campground Data', 400);
const campground = new Campground(req.body.campground);
await campground.save();
res.redirect(`/campgrounds/${campground._id}`)
}))
app.get('/campgrounds/:id', catchAsync(async (req, res,) => {
const campground = await Campground.findById(req.params.id).populate('reviews');
res.render('campgrounds/show', { campground });
}));
app.get('/campgrounds/:id/edit', catchAsync(async (req, res) => {
const campground = await Campground.findById(req.params.id)
res.render('campgrounds/edit', { campground });
}))
app.put('/campgrounds/:id', validateCampground, catchAsync(async (req, res) => {
const { id } = req.params;
const campground = await Campground.findByIdAndUpdate(id, { ...req.body.campground });
res.redirect(`/campgrounds/${campground._id}`)
}));
app.delete('/campgrounds/:id', catchAsync(async (req, res) => {
const { id } = req.params;
await Campground.findByIdAndDelete(id);
res.redirect('/campgrounds');
}));
app.post('/campgrounds/:id/reviews', validateReview, catchAsync(async (req, res) => {
const campground = await Campground.findById(req.params.id);
const review = new Review(req.body.review);
campground.reviews.push(review);
await review.save();
await campground.save();
res.redirect(`/campgrounds/${campground._id}`);
}))
app.delete('/campgrounds/:id/reviews/:reviewId', catchAsync(async (req, res) => {
const { id, reviewId } = req.params;
await Campground.findByIdAndUpdate(id, { $pull: { reviews: reviewId } });
await Review.findByIdAndDelete(reviewId);
res.redirect(`/campgrounds/${id}`);
}))
app.all('*', (req, res, next) => {
next(new ExpressError('Page Not Found', 404))
})
app.use((err, req, res, next) => {
const { statusCode = 500 } = err;
if (!err.message) err.message = 'Oh No, Something Went Wrong!'
res.status(statusCode).render('error', { err })
})
app.listen(3000, () => {
console.log('Serving on port 3000')
})
Hi @Nitin_Gaurav,
What I see now is that you were unable to access the mongo instance.
This is only a warning that suggests you enable access control.
You can log in as was done in the previous screen and attach the output of the following command:
show dbs
The database you should have populated should be called yelp-camp.
Regards
Hey Fabio, I’ve resolved the problem, thanks to you! I used the ‘show dbs’ command, which gave me the idea to move forward and access my database. Thank you!
Hey @Nitin_Gaurav,
Super!
When you have a moment, mark the solution!
Best Regards
Using the show dbs
command helps to view all the databases. You can then access a specific database by using the use [database_name]
command, which allows you to work with that particular database where I located the file.
Thanks.