简体   繁体   中英

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.

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM