javascript - 使用聚合函数 mongoose 检索特定电视节目剧集的所有信息,包括演员和导演
问题描述
我想检索特定电视节目剧集的所有信息,包括演员和导演。
这是我的电视节目 model.js:
const tvShowSchema = new Schema({
name: String,
year: Number,
country: String,
seasons: [{
number: Number,
year: Number,
episodes: [{
title: String,
number: Number,
releasedOn: Date,
description: String,
cast: [{
type: Schema.Types.ObjectId,
ref: 'actors'
}],
director: {
type: Schema.Types.ObjectId,
ref: 'directors'
}
},
{
timeStamps: true,
versionKey: false
}
]
}]
});
这是电视节目 Routes.js:
router.get("/showid/tvepisodeid/:tvshowid/seasonid/:seasonId/episodeid/:episodeId",
tvShowsCtrl.getTvShowEpisode);
这是电视节目 controller.js:
import TVShow from "../models/TVShow";
import {
Types
} from "mongoose";
export const getTvShowEpisode = async (req, res) => {
try {
const id = req.params.id;
const seasonId = req.params.seasonId;
const episodeId = req.params.episodeId;
const tvShowEpisode = await TVShow.aggregate([
{
$match: {
"_id": Types.ObjectId(id),
"seasons._id": Types.ObjectId(seasonId),
"episodes._id": Types.ObjectId(episodeId)
}
}, {
$addFields: {
"isEpisode": {
$eq: ['$seasons.episodes', selectedEpisode]
}
}
}, {
$addFields: {
"cast.isEpisode": {
$eq: ['$seasons.episodes', selectedEpisode]
}
}
}, {
$lookup: {
from: 'actors',
localField: 'seasons.episodes.cast',
foreignField: '_id',
as: 'actors'
}
},
{
$addFields: {
"director.isEpisode": {
$eq: ['$seasons.episodes', selectedEpisode]
}
}
}, {
$lookup: {
from: 'directors',
localField: 'seasons.episodes.director',
foreignField: '_id',
as: 'director'
}
},
/* {$unwind: '$seasons'}, */
{
$match: {
"seasons._id": Types.ObjectId(seasonId)
}
}, {
$project: {
"_id": Types.ObjectId(id)
},
"episode": '$seasons.episodes'
}
]);
if (tvShowEpisode) {
res.send(tvShowEpisode);
} else {
res
.status(404)
.send({
mensaje: `tv show episode not found`
});
}
} catch (error) {
console.log(error);
res.status(500).send({
message: `error: \n\n${error}`
});
}
};
预期的输出应该是这样的:
{
"seasons":[
"number":1,
"year":2019,
"episodes":[
"title":"the restaurant",
"number":2,
"releasedOn":"2019-05-10T14:00:00.025Z",
"description":"the restaurant is new",
"cast":[
{
"_id":"84834h4hrtbb54y4hu4u5h9",
"fullName":"Keith Price",
"age":25,
"nationality":"american"
},
{
"_id":"82j4hy43u45hu54huuh539",
"fullName":"Cindy Kat",
"age":28,
"nationality":"welsh"
}
],
"director":{
"_id":"urirnjr43u242344343",
"fullName":"maurice klossman",
"nationality":"polish"
}
]
]
}
我该如何解决这些问题?,为什么代码不起作用?,我想在输入 url 时传递相应的参数得到预期的输出,但在邮递员中我收到消息“500 内部服务器错误”。
我有一些问题。我尝试了很多方法,使用聚合函数只显示特定的电视节目,包括演员和导演,但我不知道如何编写代码。
我想知道我的电视节目控制器方法有什么问题。
日志错误:“参数必须是聚合管道运算符”
解决方案
推荐阅读
- jquery - 如何在单个按钮上显示两个值的可点击百分比
- amazon-web-services - AWS 政策不尊重
- vb.net - 在本地在特定浏览器中打开 url
- vb.net - Excel文件不会被代码更新,直到我手动进入并保存它。然后代码确实有效
- sql - 如何读取 groovy-sql 语句中的每一行?
- html - 带有文本椭圆的编号列表也隐藏了订单号
- c# - 激活器创建通用实例
- sql - 当两个或多个条件为真时如何取反
- google-chrome - engine: 'chrome' 和 engine: 'chromy' 在 backstop.config 有什么区别?
- javascript - 如何从事务保存搜索/Suitescript 搜索中获取销售订单“shipaddresslist”值?