【问题标题】:configure populated data after saving in mongoose保存在猫鼬中后配置填充数据
【发布时间】:2018-05-04 20:03:36
【问题描述】:

我正在使用 nodejs 和 mongo db 进行用户注册,问题是当我将所有数据插入到集合中时,它会返回文档中的所有数据我想限制一些对象返回数据,例如下面的用户对象示例包含我应该限制的密码,

newUser =  new UserSchema({
   firstName : firstName,
   middleName : middleName,
   lastName : lastName,
   email : email,
   location : location,
   password : password,
   createdDate :new Date(Date.now()).toISOString(),
   role : "user"
})
password : { // in scehma
   type: String,
    select :false,
    hide: true,
    required:true
 },
newUser.save((err,user) => {
    if(err){
        return false;
    }else{
        return user ; // user object should not have password in this 
    }
});

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    只需将select:false 与您定义架构的密码字段一起输入即可。

    喜欢:

    password : {type : String, select : false}
    

    所以它不会返回密码文件。

    【讨论】:

    • 我仍然在获取密码字段,我刚刚删除了我的收藏并重新启动了数据库服务器,结果仍然相同
    • 只需使用 db.collection.dropIndex() 从该特定集合中删除索引,然后再次启动服务器。现在您无法获取密码字段。
    【解决方案2】:

    mongoose-hidden 这个插件对我有帮助,但无论如何 select:false 应该可以工作,如果长时间尝试后不行,你可以使用上面的插件

    【讨论】:

      【解决方案3】:

      您可以做的是,在返回此用户之前,您可以删除其中的密码。如下所示

      newUser.save((err,user) => {
          if(err){
              return false;
          }else{
              user = user.toObject();
              delete user.password;
              return user ; // Now user object do not have password field 
          }
      });
      

      【讨论】:

      • 我在整个应用程序中都有不需要为所有 API 调用填充的字段
      • 那么我认为最好的解决方案是使用@vaibhavpatil 给出的答案。
      猜你喜欢
      • 2012-11-11
      • 2016-06-10
      • 1970-01-01
      • 2014-09-06
      • 2020-05-09
      • 2015-04-01
      • 2015-09-30
      • 2020-01-30
      • 2015-07-13
      相关资源
      最近更新 更多