Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.97k stars 3.84k forks source link

Populate virtual with localField reference to itself after filling it via its getter function #7471

Open alumpe opened 5 years ago

alumpe commented 5 years ago

Do you want to request a feature or report a bug? Feature

What is the current behavior? If you want to populate a virtual field which also has a getter function you can't set localField to the virtual property itself and call populate() for the virtual with the option to apply getters first.

Got this schema:

DocumentSchema = new mongoose.Schema(
    {
        version: { required: true, type: Number },
        name: { required: true, type: String },
        users: {
            required: true,
            type: [
                {
                    uid: { required: true, type: String },
                    role: { required: true, type: Number }
                }
            ]
        },
    },
    { minimize: false }
);

What I am trying to do is attaching a virtual property owner to the document which yields the uid of the array element from users with role: 0. I then want to populate the owner field with the actual document of the owner. This could be the virtual property:

WhiteboardSchema.virtual("owner", {
   ref: "User",
   localField: "owner",
   foreignField: "uid",
   justOne: true
}).get(() => {
   return // the uid of the element with role: 0 from users array
});

It would be nice if you could fill a virtual property with a value calculated from other fields (using the virtuals getter function) and then call populate on the same virtual to fill it with a doc from another collection.

Or is there any other clever solution to my problem?

vkarpov15 commented 5 years ago

There isn't a solution for this right now. We should allow having a way to set getters on populate virtuals