node.js - 从猫鼬的对象数组中删除一个对象?
问题描述
我有这些数据,我想在使用补丁请求时根据其标题删除给定的电影
"_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;
解决方案
推荐阅读
- python - 有没有办法在熊猫数据框中显示分类自变量的回归系数?
- kubernetes - 如何应用 Nginx 入口速率限制?
- java - 具有扩展实体管理器或同步点(多次提交)的 Quarkus 应用程序
- azure-cosmosdb - 欺诈场景的建模图数据库
- google-cloud-platform - 如何通过谷歌云中的对等 vpc 连接导出特定路由?
- video - FFMPEG 多次剪切并连接它们?
- powershell - 使用条件一次运行多个命令行
- java - 如何同步和更新非规范化的 cassandra 表
- laravel-8 - 如何检查请求是否具有二级 url
- bash - tmux 插件长时间运行的任务问题