2016-03-07 68 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); 
     } 
    )}; 
    } 
    }; 

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

如果您使用令牌,我强烈建议,那么该方法非常相似。我也很乐意解释一些。