I have following schema where the item type might vary, and is mentioned in connections.kind.

var userSchema = new Schema({
  name: String,
  connections: [{
    kind: String,
    item: { type: ObjectId, refPath: 'connections.kind' }

var organizationSchema = new Schema({ name: String });

I am trying to do a dynamic lookup so that the item object is populated. But this doesn't seem to work.

            from: '$connections.kind',
            localField: 'connections.item',
            foreignField: '_id',
            as: 'items'

I know I can do it with mongoose.populate, but want to know if it is possible with $lookup

Solution 1

As of now, you can't. The from field cannot be an expression and must be a string literal. However, there is an open issue which you can track here that appears to be exactly what you need: https://jira.mongodb.org/browse/SERVER-22497.