G. BARRANCO
G. BARRANCO

Reputation: 13

function is not a function

I'm trying to write an application with NodeJS / Express. When the method MealApi.massAdd is called, I have a response MealApi.massAdd is not a function. But I can't understand why. Can someone explain me this stange behaviour, please ?

This is what I have in my app.js :

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const mongoose = require('mongoose')
const MealApi = require('./api/meal')
const mealModel = require('../models/meal')

// Create connection to MongoDB
mongoose.connect('mongodb://localhost:27017/diet')

let db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error'))
db.once('open', (callback) => {
   console.log('connection succeeded')
})

// Create Express app
const app = express()
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(cors())

app.post('/meals/massAdd', (req, res) => {
  res.send(MealApi.massAdd(req.body.meals))
})

Here is my api/meal.js :

const MealModel = require('../../models/meal')

class Meal {
  massAdd (meals) {
    meals.forEach((meal) => {
      let model = new MealModel(meal)
      model.save((error) => {
        if (error) { console.error(error) }
          return {
            success: true,
            message: 'Meal ' + meal.name + ' successfully added !'
        }
      })
    })
  }
}

module.exports = Meal

Thank you very much

Upvotes: 0

Views: 90

Answers (1)

Rom
Rom

Reputation: 1838

Add static keyword before massAdd to make massAdd is static method

This is simple static method demo for you:

class A {
    static doSomething(m) {
        console.log(m);
    }
}

A.doSomething(5); 

Upvotes: 1

Related Questions