Необработанное отклонение обещания - Машинопись с h express и мангустом - PullRequest
0 голосов
/ 02 августа 2020

Пожалуйста, подождите, я новичок в node и асинхронные c вещи для меня все еще непонятны. У меня есть приведенный ниже фрагмент кода, и теперь я работаю над последней частью - маршрутом / new-comp. Предполагается разместить в базе данных, которую я подключил выше:

import { Schema } from 'mongoose'
export const mongoose = require('mongoose')

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const urlEncodedParser = bodyParser.urlencoded({ extended: false })

mongoose.connect('mongodb://localhost:27017/CompetitionEvent')
export const db = mongoose.connection
db.on('error', console.error.bind(console, 'An error has occured: '))
db.once('open', function () {
  console.log('Connected to Mongodb')
})

const CompetitionSchema = new Schema({
  id: String,
  place: String,
  time: String,
  subscriptions: [],
  date: Date,
  cost: {
    currency: String,
    amount: Number,
  },
})

const CompetitionModel = mongoose.model('CompetitionModel', CompetitionSchema)

app.use(bodyParser.json())
app.get('/events', (_req: any, res: any) => {
  res.send(eventApplication.getAll())
})

app.post('/event', async (req: any, res: any) => {
  await eventApplication.createAnEvent(req.body)
  res.json({
    success: true,
  })
})

app.post('/new-comp', urlEncodedParser, async (res: any, req: any) => {
  await eventApplication.createAnEvent(req.body)
  const newComp = CompetitionModel(req.body)
  newComp.save(function (error: any, data: any) {
    if (error) throw error
    res.json(data)
  })
})

app.listen(8000)

У меня также есть этот файл со всеми моими классами:

export interface Subscription {
  id: string
  event_id: string
  name: string
  surname: string
}
export interface EventDTO {
  id: string
  place: string
  time: string
  subscriptions: Subscription[]
  date: Date
  cost: EventCost
}
export interface EventCost {
  amount: number
  currency: string
}
export class CompetitionEvent {
  public subscriptions: Subscription[]
  public place: string
  public time: string
  public date: Date
  public cost: EventCost
  public id: string
  static save: any

  constructor(data: EventDTO) {
    this.subscriptions = data.subscriptions
    this.place = data.place
    this.time = data.time
    this.date = data.date
    this.cost = data.cost
    this.id = data.id
  }
  public isCompleted = () => this.place === 'Poznan' && this.date === new Date()

  public getSubs = () => this.subscriptions

  public subscribe = (sub: Subscription) => {
    this.subscriptions = [...this.subscriptions, sub]

    return this
  }

  public cancelSubscription(subscription: Subscription) {
    const subExists = this.subscriptions.find(
      (it) => it.id === subscription.id && it.name === subscription.name,
    )
    if (!subExists) {
      throw new Error('Subscription does not exist.')
    }

    this.subscriptions = this.subscriptions.filter(
      (it) => it.id !== subscription.id,
    )
  }
}

Теперь моя проблема в том, что когда я публикую некоторые данные в мое приложение с помощью curl, у меня есть сообщение об ошибке от сервера:
(узел: 3264) UnhandledPromiseRejectionWarning: TypeError: Невозможно прочитать свойство 'подписки' неопределенного
Я не уверен, как понимать этот журнал. Похоже, у меня где-то есть необработанное обещание (я получаю строки в журнале, но иногда оно указывает на пустые строки в моей программе ". Вы хоть представляете, как мне понять / решить эту проблему? Заранее спасибо
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...