mongoosejs / mongoose-lean-virtuals

Attach virtuals to the results of mongoose lean() queries
Apache License 2.0
45 stars 24 forks source link

populated virtuals #2

Closed PsychicCat closed 6 years ago

PsychicCat commented 7 years ago

I'm not able to use virtuals on populated models. I'm guessing that is not possible yet?

vkarpov15 commented 7 years ago

Can you please clarify with some code samples? I don't understand your question

facupedrazzini commented 7 years ago
groups
        .find({})
        .populate('owner')
        .lean({ virtuals: true })
        .exec()
vkarpov15 commented 7 years ago

I still don't understand, can you provide schemas?

tahasamad commented 6 years ago
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const mongooseLeanVirtuals = require('mongoose-lean-virtuals');

const UserSchema = new Schema({
    firstname: {
        type: String
    },
    lastname: {
        type: String
    },
    bff: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        default: null
    }
}, {
    toObject: {
        virtuals: true
    },
    toJSON: {
        virtuals: true
    }
});

UserSchema.virtual("fullname").get(function() {
    if (this._fullname === undefined) {
        this._fullname = this.firstname + this.lastname;
    }
    return this._fullname;
});

UserSchema.plugin(mongooseLeanVirtuals);

const User = mongoose.model('User', UserSchema);

mongoose.connect("mongodb://localhost/test", {
    useMongoClient: true
}, function(err) {
    if (err) {
        console.log(err);
        return;
    }
    User.findOne({firstname: "Taha"}).populate("bff").lean({virtuals: true}).exec(function(err, user) {
        console.log(user.fullname);
        console.log(user.bff.firstname);
        console.log(user.bff.fullname);// **ISSUE:** Will still be undefined.
    });
});
vkarpov15 commented 6 years ago

Bug with mongoose, will be fixed in mongoose 4.13.8 :+1:

arpitbhs commented 5 years ago

I know this is closed , but I'm using mongoose v5 and i still have this problem. I'm using the same syntax as above - Model.find().populate().lean({virtuals:true}).exec(). Im getting all the 'get' virtuals, but neither of the populate virtuals. foreg. as @tahasamad mentioned, I'm getting user.fullname but not user.bff.fullname. They just come as null. If i remove lean however , i'm getting both.

Edit - nevermind it seems to be related to this PR https://github.com/vkarpov15/mongoose-lean-virtuals/pull/19. Do you have any idea when this might be released?

vkarpov15 commented 5 years ago

@arpitsr91 just released 0.3.5 with the fix