TypeError: Cannot read property 'insertOne' of undefined

I am working on the new MERN Stack Course of restaurant reviews.
Getting error while POST REQ to reviewsDAO.js

import mongodb from "mongodb"
const ObjectId = mongodb.ObjectID

let reviews

export default class ReviewsDAO {
  static async injectDB(conn) {
    if (reviews) {
      return
    }
    try {
      reviews = await conn.db(process.env.RESTREVIEWS_NS).collection("reviews")
    } catch (e) {
      console.error(`Unable to establish collection handles in userDAO: ${e}`)
    } 
  }

  static async addReview(restaurantId, user, review, date) {
    try {
      const reviewDoc = { name: user.name,
          user_id: user._id,
          date: date,
          text: review,
          restaurant_id: ObjectId(restaurantId), }

      return await reviews.insertOne(reviewDoc)
    } catch (e) {
      console.error(`Unable to post review: ${e}`)
      return { error: e }
    }
  }


  static async updateReview(reviewId, userId, text, date) {
    try {
      const updateResponse = await reviews.updateOne(
        { user_id: userId, _id: ObjectId(reviewId)},
        { $set: { text: text, date: date  } },
      )

      return updateResponse
    } catch (e) {
      console.error(`Unable to update review: ${e}`)
      return { error: e }
    }
  }

  static async deleteReview(reviewId, userId) {

    try {
      const deleteResponse = await reviews.deleteOne({
        _id: ObjectId(reviewId),
        user_id: userId,
      })

      return deleteResponse
    } catch (e) {
      console.error(`Unable to delete review: ${e}`)
      return { error: e }
    }
  }

}

trying to fix this for hours…
Please help ASAP. :frowning:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

I’m not sure I understand, are you expecting reviews to become a global variable by not declaring it? Because I don’t believe that works (it gets executed in strict mode inside a class as far as I know).

class

The class body of a class declaration is executed in strict mode.

1 Like

sure @ilenia i will follow the rule going further.

I have update the code above.

Please see the full code.

Well according to the error reviews is undefined so you must not be getting back what you expect from conn.db (or you didn’t invoke injectDB before addReview).

Based on the code you have posted I would have a hard time knowing what the issue might be though. You are using code we can’t see and we can’t see how you are using the code you did post (we pretty much just have the definition, not the usage).

2 Likes

Thank you so much @lasjorg , I am really amazed as this is my first experience with this forum.
Issue was :
i didn’t invoke injectDB before addReview

by adding below line in index.js

await ReviewsDAO.injectDB(client)

resolved the issue

I am so glad that FreeCodeCamp has provided this platform for people in need.
LOVE & RESPECT :heart:

8 Likes

Glad to have helped, happy coding!

Virtual Hugs :slight_smile:

You have all my good wishes.

Thank you, I met the same problem.

1 Like

Had the same issue. there is nothing wrong with the reviewsDAO.js file just add

await ReviewsDAO.injectDB(client)

line to the index.js and import reviewsDAO.js as follows.
index.js →

import app from "./server.js"
import mongodb from "mongodb"
import dotenv from "dotenv"
import RestaurantsDAO from "./dao/restaurantsDAO.js"
import ReviewsDAO from "./dao/reviewsDAO.js"

dotenv.config()
const MongoClient = mongodb.MongoClient

const port = process.env.PORT || 8000

MongoClient.connect(
    process.env.RESTREVIEWS_DB_URI, {
        poolSize: 50,
        wtimeout: 2500,
        useNewUrlParser: true
    })   
    .catch(err => {
        console.error(err.stack)
        process.exit(1)
    })  
    .then(async client => {
        await RestaurantsDAO.injectDB(client)
        await ReviewsDAO.injectDB(client)
        app.listen(port, () => {
            console.log(`listening on port ${port}`)
        })
    })
    

I don’t know why Mr. Beau didn’t get that error in the tutorial (MERN stack course). Please explain if someone can.

2 Likes

I didn’t watch the video but the call to injectDB is in the source code on GitHub.

But there are some comments on the video which suggest he didn’t show it. But as I said, I didn’t watch the video so I don’t know.


Edit: Not sure how we handle corrections to YT videos. But if you are absolutely sure that part is missing from the video, maybe an issue should be opened on Github.

I don’t really know much about YT but I do believe you can add text to videos after they have been uploaded. So a simple pause with some text at the appropriate time might be all that is needed.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.