0

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.

0

3 Answers 3

3

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Also make sure that Field Type should be same. Example:- String with string, ObjectId with ObjectId
1

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

Comments

0

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

3 Comments

Thanks for you answer! Changed it to 'Trial' in the from field of the lookup, doesn't have any effect. Plus, the populate function works on these schemas so I guess/hope it was not the problem.
Look at single document in Result Collection via mongodb console. Maybe mongoose use weird formating
Tried to delete the collections, corrected every uppercase characters from every models, recreated every documents. Same result. Also tried to reproduce query in mongo console, same result...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.