英文:
Correct naming of joined collection in lookup mongoose
问题
有一个与连接的集合命名有问题的问题,找不到它。
这是我们的集合模式,在这个模式中,集合transaction与ExpenseRecurring相关联:
const transaction = Schema(
{
..
...,
expenseRecurring: {
type: SchemaTypes.ObjectId,
ref: 'ExpenseRecurring',
required: false,
},
...
....
{
timestamps: true,
}
);
但是当我们想要使用它们之间的连接时,我们没有输出,这可能是一个命名问题。
const aggregate = [
{
{
$lookup: {
from: 'expenserecurrings',
localField: 'expenseRecurring',
foreignField: '_id',
as: 'expenseRecurring',
},
},
{
$unwind: '$expenseRecurring',
},
{
$match: { ...filter },
},
];
当我删除这个lookup时,所有数据都会返回。
我测试了expenserecurrings,expenseRecurrings,ExpenseRecurrings,ExpenseRecurring。
英文:
There is a problem with the naming of joined collection, which does not find it.
This is our collection schema. in which collection transaction is related to ExpenseRecurring
const transaction = Schema(
{
..
...,
expenseRecurring: {
type: SchemaTypes.ObjectId,
ref: 'ExpenseRecurring',
required: false,
},
...
....
{
timestamps: true,
}
);
But when we want to use the connection between them, we have no output. which is probably a naming problem
const aggregate = [
{
{
$lookup: {
from: 'expenserecurrings',
localField: 'expenseRecurring',
foreignField: '_id',
as: 'expenseRecurring',
},
},
{
$unwind: '$expenseRecurring',
},
{
$match: { ...filter },
},
];
When I delete this lookup, all the data is returned.
I tested expenserecurrings, expenseRecurrings, ExpenseRecurrings, ExpenseRecurring
答案1
得分: 1
请检查两个方面:
首先,由于您使用了ref: 'ExpenseRecurring',它应该与模型创建中的名称匹配,像这样:
mongoose.model('ExpenseRecurring', recurringSchema)
它们必须相同。
其次,在查找中的from字段是集合的物理名称。
例如,如果您使用了mongoose.model('ExpenseRecurring', recurringSchema),mongoose会将集合创建为expenserecurrings。因此,查找必须像这样:
$lookup: {
from: 'expenserecurrings',
localField: 'expenseRecurring',
foreignField: '_id',
as: 'expenseRecurring',
},
英文:
You should check 2 things:
First, since you use ref: 'ExpenseRecurring', it should match the name in the model creation, like this:
mongoose.model('ExpenseRecurring', recurringSchema)
They must be same.
Second, the from field in the lookup is the physical name of the collection.
For example, if you used mongoose.model('ExpenseRecurring', recurringSchema), mongoose creates the collection as expenserecurrings. So the lookup must be like this:
$lookup: {
from: 'expenserecurrings',
localField: 'expenseRecurring',
foreignField: '_id',
as: 'expenseRecurring',
},
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论