简体   繁体   English

HTTP 在 node 和 mongodb 中放置请求

[英]HTTP put request in node and mongodb

I am trying in mongoDB and node to add subscriptions to my competitionEvent object.我正在尝试在 mongoDB 和节点中向我的 CompetitionEvent 对象添加订阅。 My issue is that I can write only one subscription and not add them one after another.我的问题是我只能编写一个订阅,而不能一个接一个地添加它们。 Here is my http file:这是我的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)
})

and here is my mongo file:这是我的 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')
    })
  })

Every time I tried to change it it would either not modify the competitionEvent, not put anything or simply replace the old subscription with a new one, which makes little sense I am sure you'll agree每次我尝试更改它时,它要么不修改竞争事件,要么不添加任何内容,或者只是用新订阅替换旧订阅,这毫无意义,我相信您会同意

You need to use the $push -operator to add a new subscription to your competition.您需要使用$push -运算符向您的比赛添加新订阅。 Assuming req.body holds the new subscription, you can do:假设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)
});

First of all fix your schema for subscription mongoose.Schema like below, for better type casting:首先修复订阅 mongoose.Schema 的架构,如下所示,以获得更好的类型转换:

Optional可选的

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

Then in your competetionEvent controller either use mongo $push operator for adding event subscription at the end of the subscription or use mongo $addToSet operator for adding the subscription in the subscription field without any duplication.然后在您的competetionEvent控制器中,要么使用 mongo $push运算符在订阅结束时添加事件订阅,要么使用 mongo $addToSet运算符在订阅字段中添加订阅而没有任何重复。

Remember, $push doesn't check if the subscription is unique or not, it just pushes elements like javascript Array.push().请记住, $push不会检查订阅是否唯一,它只是推送像 javascript Array.push() 这样的元素。 On the other hand, $addToSet checks if the subscription exists or not.另一方面, $addToSet检查订阅是否存在。 If yes then it doesn't add that subscription.如果是,那么它不会添加该订阅。 If no, then it pushes it to the field Array.如果不是,则将其推送到字段 Array。

I suggest using $addToSet as it is more secure & will not create any duplicates of the same subscription.我建议使用$addToSet因为它更安全并且不会创建相同订阅的任何重复项。

CODE代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM