Ok I just understood what is wrong here and why this will never work
.
What I sent you:
const MongoClient = require("mongodb").MongoClient;
const uri = "mongodb+srv://user:password@free.abcde.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function run() {
try {
await client.connect();
const coll = client.db('test').collection('movies');
const cursor = coll.find();
await cursor.forEach(console.dir);
} finally {
await client.close();
}
}
run().catch(console.dir);
is back end code.
Copy paste this in a new folder in an index.js file and replace the URI with a valid Atlas URI. Then run
npm install mongodb
node index.js
This will work, because it’s a backend application, executed by Node.js.
What you are trying to do, is use the MongoDB Node.js driver in a front end application which is executed in the browser - so it won’t work. And even if you got it to work, that’s a terrible idea for several reasons.
- front end code is accessible by your users and can be modified. You can never trust a client. They can retrieve your URI, Atlas user and password and alter the code. It’s not safe at all.
- If you deploy this application, let’s say it’s a mobile application. It means your data model is now piloted by your mobile applications… Which may never be updated… So if you ever want to change something and alter your data model, you just can’t and you will have to deal all the time with ALL the versions you ever deployed in production in parallel. Nightmares guaranteed.
You need a secure channel between your backend code (Node.js server or Java or Python or whatever you want really) which is a trusted environment which can communicate with your Atlas cluster and your front end code. Usually, people use a REST API or a GraphQL API with some security features like authentification, tokens, TLS, etc.
Basically, you need something between your front end code - which is just your presentation layer - and your database which contains your precious data. This back end layer is where you will implement a few things:
- user authentification,
- database access,
- provide data to the clients (via API),
- implement the business logic,
- implement the rules and restrictions (doctors can edit field X but nurse can’t and admins can do anything, etc).
You can choose the traditional path and implement a back end system as I described above, or you can choose the MongoDB Realm path.
All the stuff I described above can be implemented easily in MongoDB Realm and allow your front end application to access safely your MongoDB Atlas cluster.
I implemented a free COVID-19 REST and GraphQL API using MongoDB Realm and I did 2 blog posts to explain how I did:
I hope this helps
!
Cheers,
Maxime.