我正在尝试使用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
非常感谢您
答案 0 :(得分:1)
在static
之前添加massAdd
关键字,以使massAdd
是静态方法
这是为您提供的简单静态方法演示:
class A {
static doSomething(m) {
console.log(m);
}
}
A.doSomething(5);