When I try to connect to the MongoDB this error happens. I have installed MongoDB in my package.json and all the other models but when I run the code it's connect to the port perfectly but as soon as I try to insert a collection the error happens “undertOne() is not defined”. Moviedb.js
import app from './server.js';
import ReviewsDAO from "./dao/reviewsDAO.js";
import mongodb from 'mongodb';
import dotenv from 'dotenv';
const MongoClient=mongodb.MongoClient
//Load the environment variables from the .env file
dotenv.config();
//Access the environment variables
const mongo_username = process.env.MONGO_USERNAME;
const mongo_password = process.env.MONGO_PASSWORD;
//access to the db
const uri = new MongoClient(`mongodb srv://${mongo_username}:${mongo_password}@cluster0.b5f7prn.mongodb.net/test`);
const port=4444;
MongoClient.connect(
uri,
{
maxPoolSize: 50,
wtimeoutMS: 2500,
useNewUrlParser: true
})
.catch(err => {
console.error(err.stack)
console.error("Error connecting to the database:", err.message)
process.exit(1)
})
.then(async client => {
await ReviewsDAO.injectDB(client)
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
})
Server.js:
import express from 'express';
import cors from 'cors';
import reviews from './api/reviews.route.js';
//creating web server
const app = express();
app.use(cors());
app.use(express.json());
app.use('/api/v1/reviews', reviews);
app.use('*', (req,res)=>res.status(404).json({error:"Not found"}));
//to listen to the router
app.listen( 4444, () => {
console.log(`Listening on port 4444`);
});
export default app;
I have tried debugging the code the error appears in moviedb.js in this section:
MongoClient.connect(
uri,
{
maxPoolSize: 50,
wtimeoutMS: 2500,
useNewUrlParser: true
})
.catch(err => {
console.error(err.stack)
console.error("Error connecting to the database:", err.message)
process.exit(1)
})
.then(async client => {
await ReviewsDAO.injectDB(client)
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
})
reviews.route.js:
import express from 'express';
import ReviewsCtrl from "./reviews.controller.js";
const router=express.Router();
router.route("/movie/:id").get(ReviewsCtrl.apiGetReviews);
router.route("/new").post(ReviewsCtrl.apiPostReview);
router.route("/:id")
.get(ReviewsCtrl.apiGetReviews)
.put(ReviewsCtrl.apiUpdateReview)
.delete(ReviewsCtrl.apiDeleteReview)
export default router;
CodePudding user response:
You are passing a MongoClient
instance as a uri to MongoClient.connect, which is wrong. Use this instead
MongoClient.connect(`mongodb srv://${mongo_username}:${mongo_password}@cluster0.b5f7prn.mongodb.net/test`,
{
maxPoolSize: 50,
wtimeoutMS: 2500,
useNewUrlParser: true
})