[英]Mongo $lookup return empty array
When performing a $lookup on my schemas, it always return an empty array. 在架构上执行$ lookup时,它总是返回一个空数组。 What am I doing wrong? 我究竟做错了什么?
Result Collection 结果收集
const resultSchema = new mongoose.Schema({
trial: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Trial',
required: true
}
});
Trial Collection 试用集
const trialSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
Aggregate 骨料
Result.aggregate([
{
$lookup: {
from: 'trial',
localField: 'trial',
foreignField: '_id',
as: 'x'
}
}
])
.exec()
.then(results => ({ results }))
"x" ends up being always an empty array in the end. 最后,“ x”最终始终是一个空数组。
Ok just found the answer right here: https://stackoverflow.com/a/45481516/3415561 好的,就在这里找到答案: https : //stackoverflow.com/a/45481516/3415561
The "from" field in lookup must be your collection name and not the model name. 查找中的“来自”字段必须是您的集合名称,而不是模型名称。 Therefore it's a plural word. 因此,它是一个复数词。 Here it's 这是
from: 'trials'
instead of 代替
from: 'trial'
check collection name. 检查集合名称。 In aggregate function 'trial' starts lowercase, in results collection 'Trial' starts uppercase 在汇总函数“试用”中以小写开头,在结果集合中“试用”以大写开头
In my case I had mistakenly put a $ in front of the collection name: 在我的情况下,我错误地在集合名称的前面加上了$:
{$lookup: {
from: '$users', // <- incorrect
foreignField: '_id',
localField: 'userid',
as: 'users'
}},
it needed to be 它必须是
{$lookup: {
from: 'users', // <- correct
foreignField: '_id',
localField: 'userid',
as: 'users'
}},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.