简体   繁体   English

如何在mongodb中加入集合

[英]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. 我有一个集合,其中数据由所有者存储,所有者ID也与数据一起存储。 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 . 现在,我正在获取上述数据并显示在HTML文件中。 On same html file where data are fetching, I want to show owner details on the basis of ownerId. 在要获取数据的同一HTML文件上,我想根据ownerId显示所有者详细信息。 I mean how to join two collections in mongodb? 我的意思是如何在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); } }); });`

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/ 参考链接: 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, 根据您的要求使用mongoose

On your admodel , add ref with the target (second) model name as below 在您admodel ,加上ref如下与目标(第二)型号名称

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, 然后如下更改route

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); 
      } 
   }); 
});

可以这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM