mongodb-js / mongoose-autopopulate

Always populate() certain fields in your mongoose schemas
Apache License 2.0
221 stars 36 forks source link

Select when autopopulate with refPath #45

Closed Palando closed 6 years ago

Palando commented 6 years ago

I want to autopopulate with the refPath and make a select in the populate. Since in the refPath is the referenced type, is it possible to select depending on this type? My schema:

const MentionTextSchema = new Schema(
    {
        text: String,
        mentions: [{
            index: Int32,
            length: Int32,
            type: String,
            mentionedThing: {
                type: Object,
                refPath: "mentions.type",
                autopopulate: optionsFunction,
            }
        }]
    }
);

I want to populate the mentions.mentionedThing.type and the type is in mentions.type and can be either a User or a Group. And depending on the type the select shall be different. I tried it with an options functions but I don't know how to access the refPath and if it's possible:

var optionsFunction = function() {
    if(this.GetTheType() === "User") { // how to get the refPath?
        return { select: 'nick_name' };
    }
    else if(this.GetTheType() === "Group") { // how to get the refPath?
        return { select: 'title' };
    }
};
vkarpov15 commented 6 years ago

First, your schema has a small problem, make sure you use type: { type: String }, because right now your schema says mentions is an array of strings.

const MentionTextSchema = new Schema(
    {
        text: String,
        mentions: [{
            index: Int32,
            length: Int32,
            type: { type: String },
            mentionedThing: {
                type: Object,
                refPath: "mentions.type",
                autopopulate: optionsFunction,
            }
        }]
    }
);

We don't currently have support for accessing the current options in the autopopulate function but we'll add that for a future release

Palando commented 6 years ago

Thank you for the hint with the type.

And thank you for the clearification with the autopopulate function. That would be great, when you will implement it in the future.

vkarpov15 commented 6 years ago

Fix will be in 0.8.1:

const mappingSchema = new Schema({
      city: String,
      offer: {
        type: mongoose.Schema.Types.ObjectId,
        refPath: 'city',
        autopopulate: function(opts) {
          assert.equal(opts.refPath, 'city');
          return opts;
        }
      }
    });
vkarpov15 commented 6 years ago

Fixed by https://github.com/mongodb-js/mongoose-autopopulate/commit/a905420a7d350f4fe753ae1e3dcb78be39e97875