Cathal
Cathal

Reputation: 145

Mongoose Nested Populate Not Working

So I am currently extremely confused when it comes to mongoose populating.

My data structure is as follows: User has an array of Clients, a Client has an array of loans. I am using User.find and populating the client, no problem. But then how do I populate the loans that is inside of the client? I have tried this:

Basically, the goal is to pass in an array of Clients, each client will contain a loan. But for now, I want that loan object to be empty. The Client is being populated correctly, however, the Loan reference is being passed as undefined.

app.get("/loans", IsLoggedIn, function(req, res) {
  User.findById(req.user._id).populate({path: "clients", populate: { path: "loans", model: "loan"}}).exec(function(err, user){
    if(err){
      console.log(err);
    } else{
        var amountRepaid = calcRepaid(user.clients.loans);
        console.log(user.clients.loans);
        res.render("index", {clients: user.clients, amountRepaid: amountRepaid});
    }
  });

However it doesn't seem to work, my models are listed below and any help is appreciated!

models:

Client:

var mongoose = require("mongoose");
var clientSchema = mongoose.Schema({
  loans: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: "loan"
  }],
  emailAdderess: String,
  firstname: String,
  lastname: String,
  contactNumber: String ,
  dateCreated: {type: Date, default: Date.now},
  gender: String,
})

module.exports = mongoose.model("Client", clientSchema);

User:

const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = mongoose.Schema({
  username: String,
  password: String,
  firstname: String,
  lastname: String,
  clients: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: "Client"
  }]
});
UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);

Loan:

var mongoose = require("mongoose");

var LoanSchema = mongoose.Schema({
  firstName: String,
  lastName: String,
  email: String,
  contactNumber: Number,
  amountBorrowed: Number,
  length: String,
  address: String,
  dateDue: Date,
  gender: String,
  date: { type: Date, default: Date.now },
  amountRepaid: { type: Number, default: 0},
  loanRepaid: {type: Boolean, default: false}

})

module.exports = mongoose.model("loan", LoanSchema);

Upvotes: 3

Views: 2352

Answers (2)

D. Rattansingh
D. Rattansingh

Reputation: 1667

Try this:

const User=require('../models/user') <-- change path to your user schema
const Loan=require('../models/loan') <-- change path to your loan schema

User.findById(req.user._id).populate({path: 'clients', model: Loan})

Upvotes: 0

Helder De Baere
Helder De Baere

Reputation: 450

Try this:

.populate({
    path: 'clients',
    populate: {
        path: 'clients.loans'
    }
})

Upvotes: 3

Related Questions