Update document in NodeJS and mongoose

I a have a nodeJS app with Typescript and mongoose and I am trying to update a competitionEvent document by adding a subscription to it. Here is my http file:

const express = require('express')

import * as bodyParser from 'body-parser'
// import { eventApplication } from './compositionRoot'
import { CompetitionModel } from './mongo'

export const app = express()

app.use(bodyParser.json())
// WORKS - find all events
app.get('/events', async (_req: any, res: any) => {
  const comp = await CompetitionModel.find()
  res.send(comp)
})

// WOKRS - find just one event
app.get('/events/:id', async (req: any, res: any) => {
  const searchedComp = await CompetitionModel.find(req.params)
  res.send(searchedComp)
})

// WORKS - posts a new comp event
app.post('/new-comp', async (req: any, res: any) => {
  const data = await new CompetitionModel(req.body).save()
  res.json(data)
})

app.put('/update/:id', async (req: any, res: any) => {
  const subs = await CompetitionModel.findOneAndUpdate(
    { id: req.params },
    { subscriptions: req.body },
  )
  res.send(subs)
})

Here is my mongo file:

const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost:27017/CompetitionEvent')

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

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

export const connection = () =>
  new Promise((resolve, reject) => {
    mongoose.connection.once('open', () => {
      resolve()
    })
    mongoose.connection.once('error', () => {
      reject('something went wrong')
    })
  })

I am not sure if I should make a schema for my subscriptions as well, because the subscriptions belong to the CompetitionSchema. Now the error I have when I try to use this /update/:id route is the following:
(node:9022) UnhandledPromiseRejectionWarning: CastError: Cast to string failed for value "{ id: 'whatever' }" at path "id" for model "CompetitionModel"

I am not sure which way to go to have this route working, any ideas?

Upvotes: 1

Views: 3536

Answers (1)

Spack Jarrow
Spack Jarrow

Reputation: 360

In you app.put() route, you have made a mistake in the code, you are passing the entire req.params object when you only need to pass the required parameter id:

const subs = await CompetitionModel.findOneAndUpdate(
{ id: req.params }, // <------ You are searching for req.params
{ subscriptions: req.body },
)

Fix that with this instead:

const subs = await CompetitionModel.findOneAndUpdate(
{ id: req.params.id }, // <------ req.params.id is what you should pass.
{ subscriptions: req.body },
)

Upvotes: 3

Related Questions