Home > Net >  Error: addReview is not a function in MERN application
Error: addReview is not a function in MERN application

Time:10-18

I'm following along with a tutorial to create a movie review app on the MERN stack.

When calling my API using Insomnia, I'm getting the error "ReviewsDAO.addReview is not a function"

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.MOVIEREVIEWS_NS).collection('reviews')}
        catch(e){
            console.error(`unable to establish connection handle in reviewDAO: ${e}`)
        }
    }

    static async addReview(movieId, user, review, date){
        try{
            const reviewDoc = {
                name: user.name,
                user_id: user._id,
                date: date,
                review: review,
                movie_id: ObjectId(movieId)
            }
            return await reviews.insertOne(reviewDoc)
        }
        catch(e) {
            console.error(`unable to post review ${e}`)
            return {error: e}
        }
    }

reviews.controller.js:

import ReviewsDAO from '../dao/reviewsDAO.js'

export default class ReviewsController{
   

    static async apiPostReview(req,res,next) {
        const reviewsDAO = new ReviewsDAO()
        try{
            
            const movieId = req.body.movie_id
            const review = req.body.review
            const userInfo = {
                name: req.body.name,
                _id: req.body.user_id
            }

            const date = new Date()

            const ReviewResponse = await reviewsDAO.addReview(
                movieId, 
                userInfo,
                review,
                date
            )
            res.json({status: "success"})
        }
        catch(e) {
            res.status(500).json({error: e.message})
        }
        }

The reviews collection is also not being created in MongoDB. But maybe that isn't supposed to happen until we create our first review.

Why isn't my function being called appropriately?

CodePudding user response:

You need to instantiate a ReviewsDAO object in order to call its methods.

const reviewsDAO = new ReviewsDAO()

Then you will be able to access the addReview() method

CodePudding user response:

You are calling the class method without initializing the object.

For example:

class Animal{
  function sayhello(){
   console.log("Hello")
  }
}
// I can call the sayhello method by creating an object.
var dog=new Animal()
dog.sayhello() //prints "Hello"

But in your case, you are calling the method without creating the object.

Animal.sayhello() 
// It will create an error

So initialise the object and call the method

const reviewsDAO = new ReviewsDAO()
reviewDAO.addreviews()
  • Related