0

I don't know when to use ref in schema, but recently I started to use it as it looks clean. Below is a working example.

const UserSchema = new Schema({
  credit: {
    type: Schema.Types.ObjectId,
    ref: 'Credit'
  }
})

I will just use populate like so

const response = await User.find({}).populate('Credit').exec()

But in my other case, I have to use $lookup as in other controllers the previous dev have used aggregation.

const response = await Job.aggregate([
    {
      $match: queryObj
    },
    {
      $lookup: lookupObj
    },
    {
      $lookup: {
        from: 'credit',
        localField: ??
        foreignField: ??
        as: 'credit'
      }
    }
  ])

as you can see the code above, I have to slip in this extra $lookup

{
      $lookup: {
        from: 'credits',
        localField: ??, //no idea what this should be.
        foreignField: '_id'
        as: 'credits'
      }
    }

But it still doesn't work. I got a credit property as an empty array.

Hoknimo
  • 533
  • 2
  • 6
  • 15
  • MongoDB requires the "actual collection name" as the `from` argument to lookup. This will typically be `credits` in plural. But you can always do `from: Credit.collection.name` to get the true name from the model where already loaded. – Neil Lunn May 20 '18 at 07:38
  • Tried add an `s` to make `credit` as `credits` still getting empty array. – Hoknimo May 20 '18 at 07:40
  • You basically have two reasons why 1. You're pointing at the wrong collection, and reasons are noted. 2. You don't have `ObjectId` values that actually match. If you can do a `populate()` and get a result then it's always 1. If `populate()` returns no result then it's 2. No other cause. And `localField` is of course `credit` and `foreignField` is `_id`. – Neil Lunn May 20 '18 at 07:42
  • why mark as duplicate? I believe it's not because of the plural problem at all. – Hoknimo May 20 '18 at 07:44
  • when you use populate you don't need to care about matched `ObjectId`, unless in $lookup you need that. – Hoknimo May 20 '18 at 07:52
  • `{ $lookup: { from: 'credits', localField: 'credit' foreignField: '_id' as: 'credit' } }` try this – Ashh May 20 '18 at 08:14

0 Answers0