Search code examples
mongoosemongoose-schemamongoose-populate

Mongoose: Populating a nested array of ids


I've been looking the web for a solution and I can't seem to find an answer to my problem. Here's a very similar case, but for some reason my Document still doesn't get populated in my case. Here are the schemas:

Customer Schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var customerSchema = new Schema({
  _id: {type: Schema.Types.ObjectId},
  auditTrail: {type: Object},
  thirdParty: [{type: Schema.Types.ObjectId, ref: 'Thirdparty'}],
  docRefs: {type: Object},
  salesRep: {type: Array},
  commentsArr: {type: Array}
});

module.exports = mongoose.model('Customer', customerSchema);

the ThirdParty's:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var thirdPartySchema = new Schema({
  _id: {type: Schema.Types.ObjectId},
  type: {type: String},
  name: {type: String},
  vat: {type: String},
  corpoPhone: {type: String},
  corpoMail: {type: String},
  corpoWeb: {type: String},
  activityNumber: {type: String},
  addresses: {type: Array},
  contacts: [{type: Schema.Types.ObjectId, ref: 'Contact'}], // <-- ARRAY OF ObjectIds /!\
});

module.exports = mongoose.model('Thirdparty', thirdPartySchema);

and the Contact's:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var contactSchema = new Schema({
  _id: {type: Schema.Types.ObjectId},
  title: {type: String},
  role: {type: String},
  firstName: {type: String},
  lastName: {type: String},
  phone: {type: String},
  mobile: {type: String},
  email: {type: String}
});

module.exports = mongoose.model('Contact', contactSchema);

and here's my call:

Customer
    .find()
    .populate({
      path: 'thirdParty',
      populate: { path: 'contacts', model: 'Contact' }
    })
    .then(
    //... Do something
  )

And if the ThirdParty gets perfectly populated within the customer, the contacts absolutely don't... Here's a log of the "response": Log of the call

What am I doing wrong?

Thanks in advance!


Solution

  • Got it! I was missing the import statements in the models:

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var Contact = require('./contact'); // <--- THIS LINE RIGHT HERE
    
    var thirdPartySchema = new Schema({
      _id: {type: Schema.Types.ObjectId},
      type: {type: String},
      name: {type: String},
      vat: {type: String},
      corpoPhone: {type: String},
      corpoMail: {type: String},
      corpoWeb: {type: String},
      activityNumber: {type: String},
      addresses: {type: Array},
      contacts: [{type: Schema.Types.ObjectId, ref: 'Contact'}],
    });
    
    module.exports = mongoose.model('Thirdparty', thirdPartySchema);
    

    The request looks like:

    Customer
        .find()
        .populate({
          path: 'thirdParty',
          populate: { path: 'contacts', model: 'Contact' }
        })
        .then(
        documents => {
          res.status(200).json({
            message: 'Customer successfully fetched',
            customers: documents
          });
        }
      ).catch(err => res.status(404).json({message: 'No customer found!', error: err}));
    });
    

    Now my "objects" get properly populated:

    {
      "message": "Customer successfully fetched",
      "customers": [
        {
          "thirdParty": [
            {
              "addresses": [
                {
                  "street": "AVENIDA ESTADOS UNIDOS, 141",
                  "streetcomp": "",
                  "streetcomp2": "",
                  "city": "SAN BARTOLOME DE TIRAJANA ",
                  "cp": "35290",
                  "state": "PALMAS (LAS)",
                  "country": "spain",
                  "main": true
                },
                {
                  "street": "OTRA DIRECCION DUMMY",
                  "streetcomp": "",
                  "streetcomp2": "",
                  "city": "MADRID",
                  "state": "MADRID",
                  "country": "spain",
                  "main": false
                }
              ],
              "contacts": [
                {
                  "_id": "5cf0f6f2a3e9cf847c5861af",
                  "title": "Mrs.",
                  "role": "CFO",
                  "firstName": "John",
                  "lastName": "Doe",
                  "phone": "912345654",
                  "mobile": "673369900",
                  "thirdParty_id": "5cf0f6d0a3e9cf847c5861aa",
                  "addresses": [
                    {
                      "street": "AVENIDA ESTADOS UNIDOS , 141",
                      "streetcomp1": "TUNTE",
                      "streetcomp2": "",
                      "cp": "35290",
                      "city": "SAN BARTOLOME DE TIRAJANA ",
                      "state": "PALMAS (LAS)"
                    }
                  ],
                  "email": "jdoe@ketchup.com",
                  "auditTrail": {
                    "creation": {
                      "user_id": "1",
                      "creationDate": "1559213796974"
                    },
                    "modification": [
                      {
                        "user_id": "1",
                        "modifDate": "1559213833358"
                      }
                    ]
                  }
                }
              ],
              "_id": "5cf0f6d0a3e9cf847c5861aa",
              "type": "customer",
              "name": "ketchup",
              "vat": "B87451084",
              "corpoPhone": "918388544",
              "corpoMail": "obras@ferrometal.net",
              "corpoWeb": "http://ferrometalcimentaciones.es/",
              "activityNumber": "5630"
            }
          ],
          "salesRep": [
            {
              "user_id": "USER_ID to be defined",
              "dateBegin": "1559212324146",
              "active": true
            },
            {
              "user_id": "USER_ID to be defined",
              "dateBegin": "1559212324146",
              "active": false
            }
          ],
          "commentsArr": [
            {
              "user_id": "USER_ID to be changed to name",
              "comment": "this is a great customer!"
            },
            {
              "user_id": "USER_ID to be changed to name",
              "comment": "This is a test"
            }
          ],
          "_id": "5cf0f704a3e9cf847c5861b2",
          "auditTrail": {
            "modifications": [
              {
                "modificationDate": "1559211664284",
                "user_id": "A123"
              }
            ],
            "creation": {
              "creationDate": "1559211664284",
              "user_id": "A123"
            }
          },
          "docRefs": {
            "fs": [
              {
                "name": "mod 200 2018",
                "comment": "should be approved",
                "url": "www.google.com",
                "uploadDate": "1559212324146",
                "originalName": "mod200-2018.pdf",
                "mime": "pdf",
                "type": "fs",
                "typeName": "Financial Statements"
              }
            ],
            "id": [
              {
                "name": "Jose-Pedro",
                "comment": "ID Valido",
                "url": "/somehwere/else",
                "uploadDate": "1559212324146",
                "originalName": "id-jp.pdf",
                "mime": "pdf",
                "type": "id",
                "typeName": "Identification Document"
              }
            ],
            "ad": [
    
            ],
            "cd": [
    
            ],
            "pd": [
    
            ],
            "od": [
    
            ]
          },
          "active": true
        },
        {
          "thirdParty": [
            {
              "addresses": [
                {
                  "street": "CALLE MORGAN , 2 - BJ 2 B",
                  "streetcomp": "",
                  "streetcomp2": "",
                  "city": "BILBAO",
                  "cp": "48014",
                  "state": "BIZKAIA",
                  "country": "spain",
                  "main": true
                }
              ],
              "contacts": [
                {
                  "_id": "5cf0f6f2a3e9cf847c5861af",
                  "title": "Mrs.",
                  "role": "CFO",
                  "firstName": "John",
                  "lastName": "Doe",
                  "phone": "912345654",
                  "mobile": "673369900",
                  "thirdParty_id": "5cf0f6d0a3e9cf847c5861aa",
                  "addresses": [
                    {
                      "street": "AVENIDA ESTADOS UNIDOS , 141",
                      "streetcomp1": "TUNTE",
                      "streetcomp2": "",
                      "cp": "35290",
                      "city": "SAN BARTOLOME DE TIRAJANA ",
                      "state": "PALMAS (LAS)"
                    }
                  ],
                  "email": "jdoe@ketchup.com",
                  "auditTrail": {
                    "creation": {
                      "user_id": "1",
                      "creationDate": "1559213796974"
                    },
                    "modification": [
                      {
                        "user_id": "1",
                        "modifDate": "1559213833358"
                      }
                    ]
                  }
                }
              ],
              "_id": "5cf629538c2d290f39a9b18b",
              "type": "customer",
              "name": "ginegorama",
              "vat": "B95551776",
              "activityNumber": "8690"
            }
          ],
          "salesRep": [
            {
              "user_id": "1",
              "dateBegin": "1559212324146",
              "active": true
            },
            {
              "user_id": "2",
              "dateBegin": "1559212324146",
              "active": false
            }
          ],
          "commentsArr": [
            {
              "user_id": "USER_ID to be changed to name",
              "comment": "this is a great customer!"
            }
          ],
          "_id": "5cf6296a8c2d290f39a9b18c",
          "auditTrail": {
            "modifications": [
              {
                "modificationDate": "1559211664284",
                "user_id": "1"
              }
            ],
            "creation": {
              "creationDate": "1559211664284",
              "user_id": "1"
            }
          },
          "docRefs": {
            "fs": [
              {
                "name": "mod 200 2018",
                "comment": "should be approved",
                "url": "/somewhere",
                "uploadDate": "1559212324146",
                "originalName": "mod200-2018.pdf",
                "mime": "pdf",
                "type": "fs",
                "typeName": "Financial Statements"
              }
            ],
            "id": [
    
            ],
            "ad": [
    
            ],
            "cd": [
    
            ],
            "pd": [
    
            ],
            "od": [
    
            ]
          },
          "active": false
        }
      ]
    }