2015-10-30 25 views
3

下面是用貓鼬/節點我的要求 - 如果他們14過去中創建搜索具有大於14天前創建的日期用戶,然後更新過期的領域

用戶只能登錄到系統。如果用戶正在嘗試登錄並且他們在14天內,則他們不再有效,需要向管理員申請延期。

我想要做什麼(無論這是否正確)是在獲取所有用戶時,搜索那些在14天或更早前創建的用戶,並將過期字段設置爲true(我可以在我身份驗證,我也希望這在UI中顯示一個單獨的表,只顯示過期的用戶)。

我最初認爲在createdDate字段中設置'expires'會起作用,但是刪除了我不想要的記錄。

這是我的UserSchema和我目前的getAllUsers函數。我沒有任何東西可以嘗試解決這個問題。

var UserSchema = new Schema({ 
    name: String, 
    email: { type: String, lowercase: true }, 
    role: {type: String, default: 'user' }, 
    hashedPassword: String, 
    provider: String, 
    salt: String, 
    assignedFile: Schema.Types.Mixed, 
    createdDate: { type: Date, default: Date.now }, 
    expired: Boolean 
}); 

exports.index = function(req, res) { 
    User.find({}, '-salt -hashedPassword', function (err, users) { 
    console.log(users) 
    if(err) return res.status(500).send(err); 
    res.status(200).json(users); 
    }); 
}; 
+1

你想在用戶嘗試登錄時進行檢查嗎?即用戶試圖登錄,你用用戶ID查詢數據庫,如果用戶是14天以上,那麼你添加過期的字段?還是你想要一個正在運行的服務來每天檢查所有用戶並將過期的字段添加到適用的服務? – inspired

回答

4

要在日期篩選,您將需要$lt$lte。您還需要動態地設置過濾日期。例如:

var now = new Date(); 
// Set the date 14 days in the past 
now = new Date(now.setDate(now.getDate()-14)); 

這將返回所有誰不超過14天登錄的用戶:

User.find({createdDate: {$lte: now}}, '-salt -hashedPassword', function (err, users) { 
    console.log(users); 
    if(err) return res.status(500).send(err); 
     res.status(200).json(users); 
}); 

如果要更新expired布爾,你將需要更新多個文檔,這樣:

// $set allows you to update one or more values without updating the whole document 
// multi: true allows you to update multiple documents at the same time 
User.update({createdDate: {$lte: now}}, {$set: {expired: true}}, {multi: true}).exec(function (err, users) { 
    console.log(users); 
    if(err) return res.status(500).send(err); 
     res.status(200).json(users); 
}); 

上述功能只更新文件。如果你想每天自動運行這個函數,你需要在cronjob中「調用」這個函數。

+3

你打敗了我。很好的回答! – inspired

+0

謝謝!這個答案很完美! – mattblac

相關問題