Reputation: 684
I want to display the users from my database in MongoDB Atlas. I have successfully created a connection but am not able to show the users. It's my first time using MongoDB Atlas as well as Express.
It's working completely fine on my system with MongoDB on my system but not with MongoDB Atlas.
Here are some codes that I wrote to connect and display the users.
mongoose.connect("mongodb+srv://wulforr:<my password here>@cluster0-rpwjk.mongodb.net/test?retryWrites=true&w=majority" ,{useNewUrlParser: true, useCreateIndex: true})
.then(()=>{
console.log("connected to db");
})
.catch((err)=>{
console.log("error:",err);
})
let userSchema = new mongoose.Schema({
name: String,
email: String,
credits: Number
})
let User = mongoose.model("user", userSchema);
app.get("/users", function (req, res) {
// finding the information about all users from the database
User.find({}, function (err, response) {
if (err) {
console.log(err);
}
else {
res.render("users.ejs", { result: response });
}
})
})
I have given 0.0.0.0/0 as an IP address in MongoDB Atlas so that anyone can excess it.
A view of my MongoDB atlas collection:
Expected output:
Given output by Heroku:
What is it that I am doing wrong?
Upvotes: 5
Views: 4480
Reputation: 76
I had the same error, the connection to mongoDB Atlas was ok, but I didn't get any data from the dabatase I had created.
This problem is because of the connection string was pointing to a database called test by default, as you can see after @cluster0-rpwjk.mongodb.net/.
mongodb+srv://wulforr:<my password here>@cluster0-rpwjk.mongodb.net/test?retryWrites=true&w=majority
So I solved the issue changing the connection string to point to my database name
mongodb+srv://wulforr:<my password here>@cluster0-rpwjk.mongodb.net/MY_DATABASE?retryWrites=true&w=majority
Upvotes: 6