mongoose - 如何通过查找获取另一个集合的信息
问题描述
我有 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)})
在这个链接中我写了我的数据库模型。
解决方案
查看您的数据库模型,我认为您的电影模式定义中可能有不正确的 ref 字符串。在您的电影架构中,您拥有:
stars:[{
type: Schema.Types.ObjectId,
ref: 'userSchema'
}],
但您的用户模型定义为:
var User = mongoose.model('user', userSchema);
您的ref
电影模式中的 需要引用您给用户模型的名称,在这种情况下'user'
不是userSchema
推荐阅读
- wordpress - Reorder title tag and description tag with wpseo_title and wpseo_metadesc
- html - ajax成功中的函数调用不起作用
- android - onSharedPreferenceChanged() 仅在首次启动时调用 - 这是 Android 错误吗?
- reactjs - How to cast type on imported react component?
- c# - 更改 DataTable 行值后更新 DataGrid
- python - 如何使用不同的值更新相同的标签?
- c# - 矩阵的 C# 运算符重载
- c# - ImageBrush myBrush = new ImageBrush(); 不能在 VS C# 中工作
- html - 无效的属性值 Css 值
- python - 如何在没有换行符的情况下在没有缓冲的情况下在 Python 2.7 中打印