【问题标题】:Update document in NodeJS and mongoose在 NodeJS 和 mongoose 中更新文档
【发布时间】:2020-08-21 15:38:16
【问题描述】:

我有一个带有 Typescript 和 mongoose 的 nodeJS 应用程序,我正在尝试通过添加订阅来更新 CompetitionEvent 文档。 这是我的 http 文件:

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)
})

这是我的 mongo 文件:

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')
    })
  })

我不确定是否也应该为我的订阅创建一个模式,因为订阅属于 CompetitionSchema。现在,当我尝试使用此 /update/:id 路由时出现的错误如下:
(node:9022) UnhandledPromiseRejectionWarning: CastError: Cast to string failed for value "{ id: 'whatever'}" at path "id" for model "CompetitionModel"

我不确定这条路线要走哪条路,有什么想法吗?

【问题讨论】:

    标签: node.js mongodb typescript express mongoose


    【解决方案1】:

    在你app.put()路由中,你在代码中犯了一个错误,当你只需要传递所需的参数id时,你传递的是整个req.params对象:

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

    改用这个来解决这个问题:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-09
      • 2022-01-22
      • 2013-03-30
      • 2018-12-29
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多