【问题标题】:how to get information of another collection with lookup如何通过查找获取另一个集合的信息
【发布时间】:2019-04-13 19:43:08
【问题描述】:

我有 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)})

this link 中,我编写了我的数据库模型。

【问题讨论】:

    标签: mongoose aggregation


    【解决方案1】:

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

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

    但您的用户模型定义为:

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

    电影架构中的 ref 需要引用您为用户模型指定的名称,在这种情况下是 'user' 而不是 userSchema

    【讨论】:

      猜你喜欢
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多