节点JS-检查mongo DB中是否存在字段

时间:2016-03-06 22:04:19

标签: node.js mongodb mongoose

我不确定自己是否走在正确的轨道上,但这就是我所拥有的......

router.post('/login', function(request, response) {
    User.find({ 'username': request.body.email,'email':request.body.pwd }, function(err, user) {
    //do not know what to add here

我从两个输入字段中获取POST数据,然后使用find命令检查我的mongo数据库中是否已存在此字段。

User是我创建的模型架构。它看起来如此......

var Schema = new mongoose.Schema({
    email    : String,
    password : String,
    display  : String   
});
var User = mongoose.model('User', Schema);

我认为我在正确的轨道上,但我不确定在find命令中添加什么。如果两个字段一起存在,我想做一件事,如果不是我想抛出错误,我该怎么做?

2 个答案:

答案 0 :(得分:6)

我建议使用findOne而不是find,因为它会返回单个文档(如果存在),否则为null

router.post('/login', function(request, response) {
   // use `findOne` rather than `find`
   User.findOne({ 
    'username': request.body.email,
    'email':request.body.pwd }, function(err, user) {
      // hanlde err..
      if (user) {
        // user exists 
      } else {
        // user does not exist
      }
   })
 })

答案 1 :(得分:2)

您在查询中使用了find,这意味着您正在尝试查找所有匹配的用户,并期待来自mongodb的一组用户。

如果未找到,则用户变量将为空数组。

如果您只是想让浏览器知道请求没问题,密码匹配数据库记录并找到用户,您可以执行以下操作:

router.post('/login', function(request, response) {
    User.find({ 'username': request.body.email,'email':request.body.pwd },
    function(err, user) {
    //do not know what to add here
        if (user.length === 0) {
          return response.status(403).send("Unauthorized");
        }

        return response.status(200).send("OK");
    }

P.S。 此外,您可以使用mongoose findOne查询来进行用户登录。

相关问题