TypeError: Cannot read property 'collection' of undefined at app.post (/home/niko/Desktop/opa/app.js:17:38) at Layer.handle [as handle_request] (/home/niko/Desktop/opa/node_modules/express/lib/router/layer.js:95:5) at next (/home/niko/Desktop/opa/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/home/niko/Desktop/opa/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/home/niko/Desktop/opa/node_modules/express/lib/router/layer.js:95:5) at /home/niko/Desktop/opa/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/home/niko/Desktop/opa/node_modules/express/lib/router/index.js:335:12) at next (/home/niko/Desktop/opa/node_modules/express/lib/router/index.js:275:10) at expressInit (/home/niko/Desktop/opa/node_modules/express/lib/middleware/init.js:40:5) at Layer.handle [as handle_request] (/home/niko/Desktop/opa/node_modules/express/lib/router/layer.js:95:5)
Asked
Active
Viewed 75 times
0
-
"let db;" ; `db` doesn't point to MongoDB connection. Create connection to MongoDB and use later. – Tushar Gupta - curioustushar Jul 08 '21 at 06:10
-
https://stackoverflow.com/questions/10656574 – Tushar Gupta - curioustushar Jul 08 '21 at 06:11
2 Answers
1
Yo have created client from mongodb connection. So, you have to use client instead of db like this:
app.post('/', async (req, res, next) => {
const dataJson = req.body;
try{
const createdUser = await client.collection("users").insertOne(dataJson);
res.json(createdUser);
console.log(createdUser);
}catch(err){
console.log(err);
res.json(err);
}
});
For more information, please visit : https://docs.mongodb.com/drivers/node/fundamentals/connection/

Urvesh Nimavat
- 326
- 1
- 6
0
Out of context, but you shouldn't be posting your Mongo Connection Uri( mongodb+srv://Niko:@cluster0.k8ckw.mongodb.net/myFirstDatabase?retryWrites=true&w=majority) to public. I tried it and it works. Use dotenv to secure your secrets

r_dmr
- 154
- 1
- 7