檢查

2016-03-03 16 views
1

我使用以下節點JS存儲在數據庫中的值...檢查

//connect to database 
db.on('error', console.error); 
db.once('open', function() { 

    router.post('/register', function(request, response) { 
     //create schema 
     var Schema = new mongoose.Schema({ 
      email : String, 
      password : String, 
      display : String 
     }); 

     var User = mongoose.model('User', Schema); 
     //add POST values to schema 
     new User({ 
      email: request.body.rEmail, 
      password: request.body.rPwd, 
      display: request.body.rDName 
     //store in database 
     }).save(function(err, doc) { 
     if (err) 
      throw err; 
     else 
      console.log('save user successfully...'); 
     }); 
    }); 
}); 

在這個文件中,我想包括另一個POST方法讓我可以檢查我的數據庫中是否存在輸入值。

我有另一種形式,看起來像這樣在玉石......

form(class="inputs", action="/login", method="post") 
    input(type="text", name="email",class="form-control", id="emailLogin", placeholder="Queen's Email") 
    input(type="submit",name = "homePage" class ="loginButton" value="Log In" id="loginButton") 

name=email被提交後,我要檢查是否在數據庫中存在的價值email下,這是request.body.rEmail上述模式User

我知道我必須添加其他功能,看起來像這樣...

router.post('/login', function(request, response) { 
\\no idea 

但我不知道里面添加。在php中這是相對容易的,但研究節點往往導致我不清楚的解決方案。

回答

0

email: {type: String, required: '{PATH} is required.', unique: true}

如果您設置模型這樣,你可以說這是唯一在這裏。如果嘗試插入重複項,Mongoose將返回錯誤。

http://mongoosejs.com/docs/2.7.x/docs/schematypes.html

+0

這是有幫助的,但我不知道這是否回答我的問題,也許你可以澄清這對我來說。上面使用的模式註冊用戶並將他們的信息存儲到數據庫。然後我有另一個允許用戶登錄的表單。如果他們已經有賬戶(即他們的信息已經存儲),那麼他們可以登錄。 – Bolboa

+0

我想我誤解了一下。你可以使用像這樣的東西,如果它是重複的,登錄而不是註冊,就會出錯。 'res.redirect( '/登錄');' – neilsimp1