2016-03-07 69 views
0

我想按照以下描述獲取nodejs應用程序中的數據。
user.js,userProfile是貓鼬的模型。貓鼬 - 從多個集合中獲取數據

user.js的

var userSchema = new Schema({ 
     nick_name:{type:String}, 
     email: {type: String}, 
     password: {type: String}, 
     is_active:{type:String,enum:['1','0'],default:"1"}, 
    },{ collection: 'user'}); 

userProfile.js

var userProfileSchema = new Schema({ 
     user_id:{type:Schema.Types.ObjectId, ref:'User'}, 
     first_name:{type:String}, 
     last_name:{type:String}, 
     address:{type:String}, 
     country:{type:String}, 
     state:{type:String}, 
     city:{type:String}, 
     gender:{type:String,enum:['m','f','o'],default:"m"}, 
     is_active:{type:String,enum:['1','0'],default:"1"}, 
    },{ collection: 'userProfile'}); 

想離開把如下

{ 
    "nick_name" : "laxman", 
    "email"  : "[email protected]", 
    "first_name" : "my first name", 
    "last_name" : "my last name", 
    "address"  : "my address", 
    "country"  : "my country", 
    "state"  : "my state", 
    "city"  : "my city", 
    "gender"  : "m", 
    } 

依賴

"express" => "version": "4.7.4", 
    "mongoose" => "version": "4.4.5", 
    "mongodb" => "version": "2.4.9", 
    "OS" => "ubuntu 14.04 lts 32bit", 

SQL查詢參考

SELECT * FROM `user` 
     left join `user_profile` 
     on user.id =user_profile.user_id 
WHERE 1 
+0

你必須使用MongoDB的map-reduce功能。這裏有一些ref鏈接。 [示例](https://www.noppanit.com/merge-documents-two-collections-together-mongodb) [StackOverflow](http:// stackoverflow。com/questions/5681851/mongodb-combine-data-from-multiple-collections-into-one-how) [MongoDB](https://docs.mongodb.org/manual/core/map-reduce/ #MapReduce-Outputoptions) – Sarju

+0

如何在貓鼬中使用它 – laxman

回答

0

回答這個問題是要依賴於你是如何做身份驗證,但我會回答這個問題,我會怎樣達到你所要求的。

首先,我會製作一個Schema,而不是有兩個單獨的。然後,取決於您的身份驗證方法,我使用令牌,您會將該數據傳遞給您在客戶端接收的任何內容。這也有助於瞭解您是否在處理HTTP請求的客戶端上使用任何東西,或者這只是一個節點應用程序。

我會盡力涵蓋這兩種方法的一些細節。

假設您使用的是Cookie,我將假設您知道如何使用Express設置會話,或者在節點頂部使用任何框架,以及假設您知道您正在儘可能正確地保護您的密碼並直接跳到api大樓。

假裝這是您服務器端的控制器,以便在登錄時對用戶進行身份驗證。

var User = mongoose.model('User'); 

exports.login = function (req, res) { 
    User.findOne({email: req.body.email), function (err, user) { 
     if (err) { 
      return res.json(err); 
     } else if (!user) { 
      return res.json({message: 'User not found.'}); 
     } else { 
      if (req.body.password === user.password) { 
       req.session.user = user; 
      } else { 
      return res.json({message: 'Invalid username or password.'}); 
      } 
     } 
    )}; 
    }; 

當然,你要確保你有一些中間件的設置,所以密碼絕對不會與用戶一起發送,但這不是問題。

一旦你有了,那麼你需要用戶數據的任何其他路線是相當簡單的。你讓另一個控制器,像這樣:

exports.profile = function (req, res) { 
if (req.session && req.session.user) { 
    User.findOne({email: req.session.user.email}, function (err, user) { 
     if (!user) { 
      res.session.reset(); 
      res.redirect('/login'); 
     } else { 
     res.locals.user = user; 
     res.render('/profile); 
     } 
    )}; 
    } 
    }; 

我沒有在服務器端渲染,但如果你使用像角,你可以拉的是到客戶端。

如果您使用令牌,我強烈建議,那麼該方法非常相似。我也很樂意解釋一些。