2017-02-16 37 views
1

我在MongoDB/Mongoose中有一個數據庫,並且我有一個用戶集合,我使用這兩個用戶進行身份驗證,並將其作爲要在前端顯示的聯繫人列表。如何從MongoDB的對象數組中的原型中刪除屬性?

當我想顯示聯繫人列表時,我不想將用戶的密碼發送給用戶,因此想在將列表發送回去之前從集合中刪除它。

所以我有這樣的事情

readAll(req, res, next) { 
    User.find() 
    .then(users => { 
     users.forEach(user => { 
     delete user.password; 
     }); 
     res.send(users); 
    }) 
    .catch(next) 
}, 

這是現在的工作;即使delete user.password返回true,它也不會刪除任何內容。 由於User是我在Mongoose中定義爲ModelSchema的類,所以密碼是原型的一部分,因此不能像這樣刪除。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

我試圖做這樣的事情 delete User.prototype.password; 但不起任何作用。

我該怎麼做? 感謝

回答

1

在查詢級別,就可以使用projection選擇/取消選擇你想要的字段即

readAll(req, res, next) { 
    User.find({}, '-password') 
    .then(users => { 
     res.send(users); 
    }) 
    .catch(next) 
}, 

或使用查詢select()方法

readAll(req, res, next) { 
    User.find().select('-password') 
    .then(users => { 
     res.send(users); 
    }) 
    .catch(next) 
}, 

另一種方法將在模式定義級別更改字段的選擇屬性,例如:

email: { type: String }, 
password: { 
    type: String, 
    select: false 
}, 
... 

和查詢正常:

readAll(req, res, next) { 
    User.find() 
    .then(users => { 
     res.send(users); 
    }) 
    .catch(next) 
}, 
+1

我didn't知道'選擇:FALSE',它完全是有道理的,謝謝! – David

相關問題