簡體   English   中英

delete屬性在node.js中不起作用

[英]delete property doesn't work in node.js

我想知道為什么我不能刪除密碼對象,控制台結果顯示密碼仍然存在,我想知道為什么。

User.comparePassword(password, user.password , (err, result) => {
  if (result === true){
    User.getUserById(user._id, (err, userResult) => {
      delete userResult.password

      const secret = config.secret;
      const token = jwt.encode(userResult, secret);

      console.log(userResult)

      res.json({success: true, msg: {token}});
    });
  } else {
    res.json({success: false, msg: 'Error, Incorrect password!'});
  }
}

您的問題有多種解決方案。 您無法從Mongoose查詢中刪除屬性,因為您得到了一些Mongoose包裝器。 為了操作對象,您需要將其轉換為JSON對象。 因此,我可以記住三種可能的方法:

1)像這樣調用toObject方法貓鼬對象( userResult ):

 let user = userResult.toObject();
 delete user['password'];

2)重新定義User模型的toJson方法:

UserSchema.set('toJSON', {
        transform: function(doc, ret, options) {
            delete ret.password;
            return ret;
        }
});

3)查詢可以返回沒有指定字段的對象,因此您無需刪除任何內容:

 User.findById(user._id, {password: 0}, function (err, userResult) {
   ...
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM