mongo中的$pull请求删除数组的元素



我有一个节点和mongo应用程序,允许用户注册比赛事件并发布对这些事件的订阅
如您在下面的mongo文件中所见,每个sub都属于一个事件:

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,
},
})
[...]

现在我所有的路线都很好,除了最后一条。我想先按事件id筛选,然后按子id筛选,以便针对我想要删除的正确订阅
然后我用$pull试图删除订阅,但它不起作用,有人知道吗
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 },
{ $push: { subscriptions: req.body } },
)
res.send(subs)
})
// WORKS - 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)
})
// TO TEST - removesa subfrom an event
app.post('update/del-sub/:event_id/:id', async (req: any, res: any) => {
const subToDel = await CompetitionModel.findOneAndUpdate(
{ event_id: req.params.event_id },
{ id: req.params.id },
{ $pull: [req.params.delete] },
)
res.send(subToDel)
})

您需要将两个条件组合在一个过滤器中,并将对象中的$pull操作作为第二个参数:

await CompetitionModel.findOneAndUpdate(
{ event_id: req.params.event_id },
{ $pull: { subscriptions: req.params.id  } })

最新更新