【问题标题】:Storing only necessary data in Sails Model在 Sails 模型中仅存储必要的数据
【发布时间】:2016-08-25 21:15:20
【问题描述】:

我是 Sails 的新手,在模型方面遇到了一个小问题。
我已经定义了一个用户模型如下:

module.exports = {  
  attributes: {
   firstName: {
     type: 'string'
   },
   lastName: {
      type: 'string'
   },
   email: {
     type: 'email',
     required: true
   },

   password: {
     type: 'String'
   },
   passwordSalt: {
     type: 'String'
   },
   projects:{
     collection: 'ProjectMember',
     via: 'userId'
   }
 }
};  

我还有一个名为 Plan 的模型,它的外键是 user:

module.exports = {
   planId: { type: 'string'},
   userId: { model: 'User'}
};  

现在计划存储所有用户数据。有什么办法可以限制计划模型只保存一些用户详细信息,如名字、姓氏、电子邮件和 projectMembers,而不是存储其他个人信息。像密码,密码盐等?

提前致谢

【问题讨论】:

    标签: node.js mongodb sails.js data-modeling waterline


    【解决方案1】:

    计划不存储用户数据,它只是存储对用户模型中找到的用户数据的引用。

    【讨论】:

      【解决方案2】:

      计划模型不会存储用户数据。它只会存储在其架构中定义的数据值,即 planId 和 userId。如果您只想返回一些用户详细信息,那么您可以这样做:

      计划模型中:

      首先在model中定义一个toApi方法:

      module.exports = {
         attributes : {
         planId: { type: 'string'},
         userId: { model: 'User'},
         toApi :toApi
      }
      };  
      
      
      
       function toAPi(){
           var plan = this.toObject();
           return {
             firstName : plan.userId.firstName,
             lastName :  plan.userId.lastName,
             email : plan.userId.email,
             projectMembers : plan.userId.projectMembers
           };
          }
      

      然后在一个方法中,这样做:

      function getUserData(){   
       Plan
          .find()
          .populate('userId')
          .then(function(data){
            return data;
          })
      }
      

      在您的计划控制器中,执行以下操作:

      Plan
      .getUserData()
      .then(function(userData){
        return res.ok(userData.toApi());
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-01
        • 1970-01-01
        • 2013-07-08
        • 1970-01-01
        • 1970-01-01
        • 2018-05-26
        相关资源
        最近更新 更多