首页 > 解决方案 > 如何通过查找获取另一个集合的信息

问题描述

我有 2 个集合:电影和用户。在电影中我保存了有关电影的信息,例如在电影中扮演的演员的明星。我将此字段保存为电影集合中的数组。现在我想编写一个返回星星名称的查询。但是这个名称字段保存在用户集合中。如何从另一个集合中提取数据到这个集合?我写了这个函数,但它是错误的,stars_doc 是空的。这是我的功能:

async function starsActMostMovies(){
const res = await Movie.aggregate([
    {
        $unwind: '$stars'
    }
    ,
    {
        $lookup:
        {
            from: "User",
            localField: "_id",
            foreignField : "stars",
            as: "stars_doc"
        }
    }
    ,
    {
        $group: {
            _id : '$stars' ,
            count : { $sum : 1}
        }
    }
    ,
    {$sort: {count: -1}}
])
return res
}
starsActMostMovies().then(function(result){
    console.log(result)})

这个链接中我写了我的数据库模型。

标签: mongooseaggregation

解决方案


查看您的数据库模型,我认为您的电影模式定义中可能有不正确的 ref 字符串。在您的电影架构中,您拥有:

stars:[{
type: Schema.Types.ObjectId,
ref: 'userSchema'
}],

但您的用户模型定义为:

var User = mongoose.model('user', userSchema);

您的ref电影模式中的 需要引用您给用户模型的名称,在这种情况下'user'不是userSchema


推荐阅读