Saurabh Sharma
Saurabh Sharma

Reputation: 804

How to join collections in mongodb

I have a collection where data is stored by a owner and owner id is also stored along with data. On other hand there is another collection in which owner details are stored.

{
    "_id" : ObjectId("58103aac9899ff238cbae413"),
    "id" : 10585131,
    "title" : "Edfwef EdfwefE dfwefE dfwefEd fwef",
    "category" : "Furniture",
    "condition" : "Brand New",
    "brand" : "Samsung",
    "price" : "3434",
    "description" : "sdvsdfv",
    "date" : ISODate("2016-10-26T05:10:04.240Z"),
    "ownerId" : "40903aac9899er238cbae598",
    "__v" : 0
}

Now I am fetching above data and showing on a HTML file . On same html file where data are fetching, I want to show owner details on the basis of ownerId. I mean how to join two collections in mongodb? Please help.

Thanks.

Updated:

admodel

`var adSchema=new Schema({ id:{type:Number}, title:{type:String, required:true}, category:{type:String}, condition:{type:String}, brand:{type:String}, price:{type:String}, city:{type:String}, town:{type:String}, description:{type:String}, image:{type:String}, date:{type:Date}, ownerId:{type:Schema.Types.ObjectId, ref: 'user'} }); module.exports=mongoose.model('ads', adSchema);`

user

`var UserSchema=new Schema({ name:{type:String, require:true}, password:{type:String, require:true, unique:true,}, email:{type:String, require:true, unique:true,}, mobile:{type:String} }); module.exports = mongoose.model('User', UserSchema);`

Inserting Data

`apiRoutes.post('/adcreate',upload ,function(req, res, next){
  var token=req.headers.authorization;
  var owner=jwt.decode(token, config.secret);
  var currentDate=Date.now();
  var adId=Math.floor(Math.random()*13030978)+1;
  var ad=new admodel({
          id:adId,
          title:  req.body.title,
          category:req.body.category,
          condition:req.body.condition,
          brand:req.body.brand,
          price:req.body.price,
          city:req.body.city,
          town:req.body.town,
          description:req.body.description,
          date:currentDate,
          ownerId:owner.id
      }) ;
    ad.save(function(err, data){
          if(err){
            return res.json({success:false, msg:'Ad not Posted'});
          }else{
            res.json({succes:true, msg:'Successfully ad Posted'});
          }
     });
});`

Fetching Data

`apiRoutes.get('/individualads/:id', function(req, res,next){ admodel.findOne({_id:req.params.id}).populate('ownerId').exe‌​c(function(err, data){ if(err){ res.json(err); } else{ console.log(data); res.json(data); } }); });`

Upvotes: 0

Views: 1099

Answers (2)

Simran
Simran

Reputation: 2830

Can do like this:

 db.owner.find({}).populate({'path':'ownerId','model':'owner'}).exec()

Upvotes: 1

Aruna
Aruna

Reputation: 12022

You can try as below and replace the properties as per your db collection

Reference Link: https://docs.mongodb.com/v3.2/reference/operator/aggregation/lookup/

// I assume 'orders' is your first collection name
    db.orders.aggregate([
        {
          $lookup:
            {
              from: "owners",    // your second collection name
              localField: "ownerId",  // matched property in first collection
              foreignField: "_id",    // matched property to join to the second collection
              as: "owner"       // owner details output property
            }
       }
    ])

Using mongoose as you requested,

On your admodel, add ref with the target (second) model name as below

ownerId: {
            type: Schema.Types.ObjectId,
            ref: 'owner'  // This should be a name of the second model name in which you want to join and fetch data
        }

Then change the route as below,

apiRoutes.get('/individualads/:id', function(req, res,next){
   admodel.findOne({_id:req.params.id}).populate('ownerId').exec(function(err, data){ 
      if(err){
        res.json(err);
      } else{ 
        console.log(data); 
        res.json(data); 
      } 
   }); 
});

Upvotes: 2

Related Questions