【问题标题】:HTTP put request in node and mongodbHTTP将请求放入节点和mongodb
【发布时间】:2020-12-16 03:14:39
【问题描述】:

我正在尝试在 mongoDB 和节点中添加对我的 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/:event_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)
})

// WORKS - posts a new subscription into a comp
app.put('/update/:event_id', async (req: any, res: any) => {
  const subs = await CompetitionModel.findOneAndUpdate(
    { event_id: req.params.event_id },
    { subscriptions: req.body },
  )
  res.send(subs)
})

// TO TEST - deletes a competition event
app.delete('/delete/:event_id', async (req: any, res: any) => {
  const toDel = await CompetitionModel.deleteOne({
    event_id: req.params.event_id,
  })
  res.json(toDel)
})

这是我的 mongo 文件:

const mongoose = require('mongoose')

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

export const CompetitionSchema = new mongoose.Schema({
  event_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('oooooh shit')
    })
  })

每次我尝试更改它时,它要么不修改竞争事件,不添加任何内容,要么只是用新订阅替换旧订阅,这没什么意义,我相信你会同意

【问题讨论】:

    标签: javascript node.js mongodb typescript express


    【解决方案1】:

    您需要使用$push-operator 为您的比赛添加新订阅。假设req.body 持有新订阅,您可以这样做:

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

    【讨论】:

      【解决方案2】:

      首先修复订阅 mongoose.Schema 的架构,如下所示,以便更好地进行类型转换:

      可选

      const CompetitionSchema = new mongoose.Schema({
        event_id: String,
        compName: String,
        place: String,
        time: String,
        subscriptions: [{
         //what ever field you wanna add
         _id: false //if you don't wanna use it as a sub-document
      }],
        date: Date,
        cost: {
          currency: String,
          amount: Number,
        },
      })
      

      然后在您的 competetionEvent 控制器中,使用 mongo $push 运算符在订阅结束时添加事件订阅,或者使用 mongo $addToSet 运算符在订阅字段中添加订阅,无需任何重复。

      请记住,$push 不会检查订阅是否唯一,它只是推送诸如 javascript Array.push() 之类的元素。另一方面,$addToSet 检查订阅是否存在。如果是,那么它不会添加该订阅。如果否,则将其推送到字段 Array。

      我建议使用$addToSet,因为它更安全且不会创建相同订阅的任何重复。

      代码

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

      【讨论】:

        猜你喜欢
        • 2017-07-29
        • 2012-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多