2016-10-28 22 views
0

我是服務器端編程的新手,我試圖理解如何發送數據服務器端,在集合中查找文檔並將其與之比較該數據,然後根據是否存在將狀態發送回客戶端。如何查找MongoDB文檔並將其與發佈到服務器的數據進行比較

這裏是什麼正在通過/login POST請求發送服務器端:

{"email":"[email protected]","password":"pass"}

這裏我想對users集合中比較我的數據庫文件:

{ 
    "_id" : ObjectId("580bcf9874ae28934705c0fc"), 
    "email" : "[email protected]", 
    "password" : "pass" 
} 

這裏是我的服務器端腳本(我猜測有問題的區域上面有註釋)

var express = require("express"); 
var app = express(); 
var bodyParser = require("body-parser"); 
var fs = require("fs"); 
var mongoose = require("mongoose"); 

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({extended: false})); 

app.use(express.static("./public")); 

mongoose.connect('mongodb://localhost:27017', function (err, db) { 

    app.post("/login", function(req, res) { 

     var emailRegex = /^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; 
     var userInDb; 

     // ***** HERE 1 ****** 
     db.collection("users").findOne({"email": req.body["email"], "password": req.body["password"]}).toArray(function(err, results) { 

      userInDb = results;   
      db.close(); 

     }); 

     // ***** HERE 2 ****** 
     var emailInDb = userInDb["email"]; 
     var passwordInDb = userInDb["password"]; 

     if (!req.body["email"] || !req.body["password"]) { 
      res.sendStatus(403); 
     } else if (!emailRegex.test(req.body["email"])) { 
      res.sendStatus(403); 
     } else if ((req.body["email"] != emailInDb) && (req.body["password"] != passwordInDb)) { 
      res.sendStatus(403); 
     } else { 
      res.sendStatus(200); 
     } 

    }); 
}); 

我也嘗試過在地方 「在這裏1」 部分的以下內容:

var findUser = function (db, callback) { 
    var users = db.collection("users"); 
    users.findOne({"email": req.body["email"], "password": req.body["password"]}).toArray(function(err, results) { 
    userInDb = results; 
    callback(results); 
}); 

================== =編輯========================

這裏是什麼樣子實現以下後:

mongoose.connect('mongodb://localhost:27017', function (err, db) { 

    app.post("/login", function(req, res) { 

     var emailRegex = /^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; 
     var userInDb; 

     if (!req.body["email"] || !req.body["password"]) { 
      return res.sendStatus(403); 
     } else if (!emailRegex.test(req.body["email"])) { 
      return res.sendStatus(403); 
     } else { 

      db.collection("users").findOne({"email": req.body["email"], "password": req.body["password"]}, function(err, results) { 

       if(err || !result) { 
       return res.sendStatus(403); 
       } else { 
       userInDb = results;    
       db.close(); 
       return res.sendStatus(200); 
       } 

      }); 

     } 

    }); 
}); 

但我得到這個錯誤[R在終端:

POST request for '/login' - {"email":"[email protected]","password":"pass"} 
TypeError: Cannot read property 'collection' of undefined at app.js:30:6 

這裏是在第30行是什麼:

db.collection("users").findOne({"email": req.body["email"], "password": req.body["password"]}, function(err, results) { 

這個集合中需要在某個地方比你安裝MongoDB的時候成立了/db/data/文件夾以外的存儲,我需要mongoose.connect直接到users集合,還是別的?

回答

0

findOne是一個異步功能,你必須把上面這裏2的代碼的回調是這樣的:

db.collection("users").findOne({"email": req.body["email"], "password": req.body["password"]}).toArray(function(err, results) { 

     // ***** HERE 2 ****** 
     var emailInDb = userInDb["email"]; 
     var passwordInDb = userInDb["password"]; 

     ..... 
}); 

然後,你忘記檢查錯誤和結果,

db.collection("users").findOne({"email": req.body["email"], "password": req.body["password"]}).toArray(function(err, results) { 

     if(err || !result) 
      res.sendStatus(403); 

      // ***** HERE 2 ****** 
      var emailInDb = userInDb["email"]; 
      var passwordInDb = userInDb["password"]; 

     ..... 
}); 

然後,你用toArray函數調用findOne,爲什麼?你只需要1個結果,你不需要改變它。此外,您不使用結果作爲數組,因此與

db.collection("users").findOne({"email": req.body["email"], "password": req.body["password"]}, function(err, results) { 

     if(err || !result) 
      return res.sendStatus(403); 

      // ***** HERE 2 ****** 
      var emailInDb = userInDb["email"]; 
      var passwordInDb = userInDb["password"]; 

     ..... 
}); 

最後替換它,蒙戈調用之前做控制,以防止無用的DB調用,無需檢查(req.body [「電子郵件」] != emailInDb)& &(req.body [「password」]!= passwordInDb),因爲它已經在mongo查詢中完成了。

最終代碼:

var emailInDb = userInDb["email"]; 
var passwordInDb = userInDb["password"]; 

if (!req.body["email"] || !req.body["password"]) { 
    return res.sendStatus(403); 
} else if (!emailRegex.test(req.body["email"])) { 
    return res.sendStatus(403); 
} else { 

db.collection("users").findOne({"email": req.body["email"], "password": req.body["password"], function(err, results) { 
     if(err || !result) 
      return res.sendStatus(403); 
     else 
     { 
      userInDb = results;    
      db.close(); 
      return res.sendStatus(200); 
     } 
    }); 
    }); 
} 

其他的優化:

你不需要把你的電話在蒙戈DB連接回調。

哈希您在DB

密碼================編輯============= 不要使用分貝。收集

文件app.js

var mongoose  = require("mongoose"); 
var User = require("./models/User"); 

mongoose.connect('mongodb://localhost:27017'); 
app.post("/login", function(req, res) { 
    var emailRegex = /^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; 
    var userInDb; 

    if (!req.body["email"] || !req.body["password"]) { 
     return res.sendStatus(403); 
    } else if (!emailRegex.test(req.body["email"])) { 
     return res.sendStatus(403); 
    } else { 

     Users.findOne({"email": req.body["email"], "password": req.body["password"]}, function(err, results) { 

     if(err || !results) { 
      return res.sendStatus(403); 
     } else { 
      return res.sendStatus(200); 
     } 
     }); 
    } 
}); 

app.listen(.... 

文件模型/ user.js的

var mongoose = require('mongoose'); 

var userSchema = new mongoose.Schema({ 
    // auth fields 
    email:  {type: String, unique: true, lowercase: true }, 
    password:  {type: String, default: ""} 
    ... other fields 
}); 

module.exports = mongoose.model('User', userSchema); 
+0

感謝您抽出時間回覆。我用更多信息更新了這篇文章。 –

+0

響應更新 – Dafuck

+0

我還不熟悉模式,所以如果這是一個愚蠢的問題,但沒有搜索該數據庫集合中的文檔,我會如何找到用戶,這是道歉? –

相關問題