我需要你的帮助,请与猫鼬查询我的快递应用程序。
我有3个集合电影,电视节目和预告片,我需要获取所有的电影或节目有预告片。以下是模型:
var TrailerSchema = new Schema(
{
link: {
type: String,
required: true,
},
movieId: { type: mongoose.Schema.Types.ObjectId, ref: 'Movie' },
showId: { type: mongoose.Schema.Types.ObjectId, ref: 'Show' },
}
)
module.exports = mongoose.model('Trailer', trailerSchema)
const mongoose = require('mongoose')
const Schema = mongoose.Schema
var movieSchema = new Schema(
{
title: {
type: String,
required: true,
},
rating: {
type: Number,
},
}
)
module.exports = mongoose.model('Movie', movieSchema)
在Trailer集合中,有些文档带有movieId字段,有些带有showId字段。现在我如何获取所有有预告片的电影或节目呢?
由于您只是将movieId
存储在TrailerSchema
中,movieSchema
没有TrailerId:[{type: mongoose.Schema.Types.ObjectId, ref: 'Trailer'}]
那样的字段,因此不能使用填充…但对于你的问题
let listOfIds = await Link.find( { movieId: { $exists: true } }, 'movieId._id' ).lean()
我不知道真实的数据存储在拖车集合查询在Trailer.find
后得到id,你应该在电影集合中搜索,以获得所有信息
let listOfMovies = await Movie.find({ _id: { $in: listOfIds.map((id) => {if(id.movieId) return id.movieId._id} ) }, })