Populate doesnt work on mongoose

I’ve been trying to populate Auth with Voters Document but it doesnt seem to work. Sorry for the long a$$ code


const voterSchema = mongoose.Schema({
    firstName: {
        type: String,
        require: [true, 'Please provide a Firstname'],
        maxLength: [true, 'Firstname must be less than 15 characters'],
        minLength: [true, 'Firstname must be greater than 3 characters'],
    },
    lastName: {
        type: String,
        require: [true, 'Please provide a LastName'],
        maxLength: [true, 'LastName must be less than 15 characters'],
        minLength: [true, 'LastName must be greater than 3 characters'],
    },
    birthday: {
        type: Date,
        require: [true, 'Please provide a birthday'],
        validate: {
            validator: function (value) {
                return validator.isDate(value);
            },
            message: 'Please provide a valid date.'
        }
    },
    address: {
        type: String,
        require: [true, 'Please provide a Address'],
        maxLength: [true, 'Address must be less than 15 characters'],
        minLength: [true, 'Address must be greater than 3 characters'],
    }, mobile: {
        type: String,
        require: [true, 'Please provide a Mobile Number'],
        maxLength: [true, 'Mobile Number must be less than 20 characters'],
        minLength: [true, 'Mobile Number must be greater than 3 characters'],
    },
    email: {
        type: String,
        unique: [true, 'Email already exists. Please provide another one'],
        require: [true, 'Please provide a Mobile Number'],
        maxLength: [true, 'Mobile Number must be less than 20 characters'],
        minLength: [true, 'Mobile Number must be greater than 3 characters'],
    },
    createdAt: {
        type: Date,
        default: Date.now()
    },
    candidate: {
        type: mongoose.Schema.ObjectId,
        ref: 'Candidate'
    },
    auth:{
        type: mongoose.Schema.ObjectId,
        ref: 'Auth'
    }
}, {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
});

voterSchema.index({candidate: 1}, {unique: true});
voterSchema.index({auth: 1}, {unique: true});

---------------------Auth Schema-----------------------------------

const authSchema = mongoose.Schema({
    username: {
        type: String,
        require: [true, 'Please provide a username.'],
        maxLength: [true, 'Only maximum of 15 characters is allowed for username'],
        minLength: [true, 'Only minimum of 4 characters is allowed for username'],
        unique: [true, 'The username already exists. Please try again!']
    },
    password: {
        type: String,
        require: [true, 'Please provide a password.'],
        maxLength: [true, 'Only maximum of 15 characters is allowed for password'],
        minLength: [true, 'Only minimum of 5 characters is allowed for password'],
        select: false
    },
    email: {
        type: String,
        require: [true, 'Please provide a password.'],
        maxLength: [true, 'Only maximum of 15 characters is allowed for password'],
        minLength: [true, 'Only minimum of 5 characters is allowed for password'],
        validate: [validator.isEmail, 'Please provide a valid email.'],
        unique: [true, 'The email already exists. Please try again!']
    },
    passwordConfirm: {
        type: String,
        require: [true, 'Please provide a password confirm.'],
        maxLength: [true, 'Only maximum of 15 characters is allowed for password confirm'],
        minLength: [true, 'Only minimum of 5 characters is allowed for password confirm'],
        validate: {
            validator: function (value) {
                return value === this.password;
            },
            message: 'Passwords doesn\'t match. Please try again!'
        }
    },
    role: {
        type: String,
        enum: ['admin', 'user'],
        default: 'user'
    },
    isActive: Boolean,    
    passwordHasChangedAt: {
        type: Date
    },
    passwordToken: String,
    passwordTokenExpiration: Date
},
    {
        toObject: { virtuals: true },
        toJSON: { virtuals: true },
    });


--------------------------------------------------------------------------
exports.getUser =  factory.getOne(Auth, {path: 'voters'});

--------------------------------------------------------------------------
exports.getOne = (Model, popOptions) => catchAsync(async (req, resp, next) =>{
    const query =  Model.findById(req.params.id);

    doc = await query.populate(popOptions);

    if(!doc){
        return next(new APIError('Document was not found. Please try again', 404));
    }

    resp.status(200).json({
        status: 'success',
        data:{
            doc
        }
    });
});

Whats popOptions?

With a quick glance at the code everything checks out, except it only works if popOptions is something of the following:

QueryPopulateOptions  {
    /** space delimited path(s) to populate */
    path: string;
    /** optional fields to select */
    select?: any;
    /** optional query conditions to match */
    match?: any;
    /** optional model to use for population */
    model?: string | Model<any>;
    /** optional query options like sort, limit, etc */
    options?: any;
    /** deep populate */
    populate?: QueryPopulateOptions | QueryPopulateOptions[];
  }

(this was copy-pasted over from my TypeScript codebase that is using mongoose.

the value can also be a string for the path to populate, among other things.

Thanks for the help man. I really appreciate it. Here’s my implementation not really sure why it’s not working. It’s not even throwing errors or warnings this is one of the things i hate on node.js/express/mongoose sometimes you dont get any errors lol it just runs. Im the verge of giving up so frustratiing lol.

This is also happening to virtual functions it wont display. It’s already 2 days and i still cant figure this out

exports.getUser = factory.getOne(Auth, {path: ‘voters’});

Another potential problem is if you don’t see anything is that mongoose can’t connect to the DB at all. This might be a long shot, but you can check when you setup when you connect that you connect to the db correctly.

If mongoose can’t connect, it might re-try and keep re-trying and never being able to fufill the requests to the DB.

Working now. I’m a bit stupid cuz i missed the virtual function on Party. Im loving NodeJS again lol

partySchema.virtual('candidates', {
    localField: '_id',
    foreignField: 'party',
    ref: 'candidate',
});

Ah, glad you figured it out tho :+1: