0xkvn
0xkvn

Reputation: 386

Mongo $lookup return empty array

When performing a $lookup on my schemas, it always return an empty array. 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.

Upvotes: 0

Views: 2410

Answers (3)

MalcolmOcean
MalcolmOcean

Reputation: 2985

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'
}},

Upvotes: 1

0xkvn
0xkvn

Reputation: 386

Ok just found the answer right here: 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'

Upvotes: 3

Artur P.
Artur P.

Reputation: 896

check collection name. In aggregate function 'trial' starts lowercase, in results collection 'Trial' starts uppercase

Upvotes: 0

Related Questions