Search code examples
mongodbmongoosemongoose-populate

How to populate documents from other collection. Specific case


How to get data from a query that involves 2 collections: customers and addresses

I need to get all customers with all addresses for all of them, querying to customers collection.

Using mongoose these are the 2 schemas:

addressescustomers:

var Customer = require('./customer');

var Schema = mongoose.Schema;

var addressSchema = Schema({
    address: {
        type: String,
        required: false,
        unique: false
    },
    customer: {
        type: Schema.Types.ObjectId,
        ref: 'Customer'
    }
}, {
    timestamps: true
});

module.exports = mongoose.model('Addresscustomer', addressSchema, 'addressescustomers');

customers:

var Addresscustomer = require ('./addresscustomer');

var Schema = mongoose.Schema;

var customerSchema = Schema({
    name: {
        type: String,
        required: false,
        unique: false
    },
    address: {
        type: Array,
        ref: 'Addresscustomer'
    }
}, {
    timestamps: true
});

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

I need to execute the query to customers, what I do is this:

Customer.find({}, function (err, customers) {
            Addresscustomer.populate(customers, { path: "address" }, function (err, customers) {
                console.log('Customers: '+ customers);
            });
        });

Or:

var query = Customer.find({}).populate('address');
query.exec(function (err, customers) {
        console.log('Customers: '+ customers);
    });

But the key address in customers collection is not filled. Can you tell me how to set correctly the schemas and the query to get the correct data?


Solution

  • You can use $lookup to populate address reference. Since Mongo 3.4 $lookup works on array field as well.

    db.customers.aggregate([
        { "$lookup": {
           "from": "addressescustomers",
           "localField": "address",
           "foreignField": "_id",
           "as": "addr"
        }}
    ])