Vishal Rana
Vishal Rana

Reputation: 11

Join two collections using mongoose and get data from both

I have two collections User and Taxdetails, I want the name and phone number from User and payment details from Taxdetails joingin on user_id in both collections.

I am doing this:

User
    .find()
    .exec(function(err, userDetails) {
        if (err) {
            console.log("error in user collection");
            res
                .status(400)
                .json({ 'message':'error','success':false });
        } else {
            var userid = userDetails.map(function(obj) { 
                return obj._id;
              });
              Taxdetail
                  .find()
                  .exec({ user_id : { $in : userid } },function(err, requests) {
                        if(err){
                            console.log("error in TaxDetails collection");
                            res
                                .status(400)
                                .json({ 'message':'error','success':false });
                        }else{
                            console.log("Success, got some data");
                            res
                                .status(200)
                                .json(requests);
                        }                     
                    });
        }
    });

Upvotes: 0

Views: 17298

Answers (1)

Molda
Molda

Reputation: 5704

You may want use referenced schema in your User schema and then populate it like this:

var taxDetailSchema = new Schema({
    title: String
});

var taxDetail = mongoose.model('taxDetail', taxDetailSchema);

var userSchema = new Schema({
  name:  String,
  taxDetails: [{ type: Schema.Types.ObjectId, ref: 'taxDetail' }]
});

Your query would look like this:

User
.find()
.populate('taxDetails')
.exec(function(err, users) {

});

The users should look like this:

[
    {
        name: 'Some Name',
        taxDetails: [
            { title: 'Some Title' },
            { title: 'Some other Title' }
        ]
    }
]

Mongoose documentation here

Hope it helps

Upvotes: 5

Related Questions