I have the following code in a file called record.js which defines routes for an express api and is contained by server.js along with app.listen(), the server listener.
const express = require(“express”);
const recordRoutes = express.Router();
const dbo = require(“../db/conn”);
recordRoutes.route(“/record”).get(function (req, res) {
let db_connect = dbo.getDb('mernit');
console.log(db_connect);
db_connect
.collection(“records”)
.find({})
.toArray(function (err, result) {
if (err) throw err;
res.json(result);
});
res.send(“hello_world");
});
This code is written according to: https://www.mongodb.com/languages/mern-stack-tutorial but with a simplified server side.
I receive the following error after ensuring server connection, console logging the db_connect object, and attempting to access the collection, "records".
TypeError: db_connect.collection is not a function
at C:\Users\bbell\projects\MERN\server\routes\record.js:20:6
at Layer.handle [as handle_request] (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\index.js:47:12)
error throws on '.collection(“records”)'...
Additionally, the Front End returns HTTP response code 500 when attempting to GET on http://localhost:3000/record.
I am using Mongo 4.4.10 with Atlas. I looked into the problem a bit and it seems the connection method may have been deprecated or reworked in some earlier version.
However, the tutorial (linked above), if up to date, would suggest the function is still valid.
Does anyone know why my route is failing to access, and how to successfully access, my database collection 'records'?
Thanks,
Brandon
CodePudding user response:
You are missing "employees" the code for this route should look like this
recordRoutes.route("/record").get(function (req, res) {
let db_connect = dbo.getDb("employees");
db_connect
.collection("records")
.find({})
.toArray(function (err, result) {
if (err) throw err;
res.json(result);
});
});
Also your res.send("hello world)
line is missing the closing quote.
CodePudding user response:
Got it after reverting some changes to the conn.js file and deleting some stray res.funcs .