首页 > 解决方案 > 从猫鼬的对象数组中删除一个对象?

问题描述

我有这些数据,我想在使用补丁请求时根据其标题删除给定的电影

    "_id": "604184234a2f37156cec63ca",
    "name": "Jacob Tremblay",
    "description": "Jacob Tremblay is a Canadian actor. He made his film debut as Blue in the live action animated film",
    "born": "06051993",
    "bornCountry": "Usa",
    "movies": [
        {
            "movie": {
                "_id": "604184384a2f37156cec63cb",
                "title": "Luca",
                "__v": 0,
                "id": "604184384a2f37156cec63cb"
            },
            "role": "Luca"
        }
    ],
    "__v": 0
}

在 mongodb 文档中,它说我可以使用 $pull 并提供 $elemMatch 来实现我想要做的事情,但我无法弄清楚它是如何完成的。我的控制器方法

const removeMovieForActor = async (req, res, next) => {
  try {
    await Actor.updateOne(
      { _id: req.params.id },
      { $pull: { movies: { movie: { $elemMatch: { title: req.params.title } } } } },
    )
    res.status(200).json({ success: true, data: 'Actor updated!' })

  } catch (error) {
    res.status(400).json({ success: false, error: error })
  }
}

演员模型

import mongoose from 'mongoose'

const ActorSchema = new mongoose.Schema({
  name: {
    type: String,
    trim: true,
    required: [true, 'Please add an actor name']
  },
  born: {
    type: String,
    required: [true, 'Please add a born date']
  },
  bornCountry: {
    type: String,
    required: [true, 'Please add a country']
  },
  description: {
    type: String,
    required: [true, 'Please add an actor description']
  },
  movies: [{
    _id: false,
    movie: {
      type: mongoose.Schema.ObjectId,
      ref: 'Movie'
    },
    role: {
      type: String
    }
  }]
})


const Actor = mongoose.model('Actor', ActorSchema);

export default Actor;

标签: node.jsmongodbmongoose

解决方案


推荐阅读