功能不是功能

时间:2018-12-11 13:53:18

标签: node.js express

我正在尝试使用NodeJS / Express编写应用程序。 调用方法MealApi.massAdd时,我得到一个响应MealApi.massAdd is not a function。但是我不明白为什么。 有人可以向我解释这种臭味吗?

这就是我的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))
})

这是我的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

非常感谢您

1 个答案:

答案 0 :(得分:1)

static之前添加massAdd关键字,以使massAdd是静态方法

这是为您提供的简单静态方法演示:

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

A.doSomething(5);