【问题标题】:mongoose find multiple documents猫鼬找到多个文件
【发布时间】:2017-06-30 13:15:58
【问题描述】:

我有一个基本的User 架构

var UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  }
});

现在我想实现dual login 功能,

  async.parallel([
    function (cb) {
      User.findOne({$and: [{name: req.body.username1}, {password: req.body.password1}]}, function (err, u) {
        if (!u)
          err = "User1 dose not exist";
        cb(err, u)
      });
    },
    function (cb) {
      User.findOne({$and: [{name: req.body.username2}, {password: req.body.password2}]}, function (err, u) {
        if (!u)
          err = "User2 dose not exist";
        cb(err, u)
      });
    }
  ], function (err, results) {
      ....

我想知道是否有一种简单的方法可以在一个User.find() 函数中找到这两个用户信息?

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongodb-query


    【解决方案1】:

    您只需使用$or。此外,您对$and 的使用在这里是多余的:

      User.find({
          "$or": [
             { "name": req.body.username1, "password": req.body.password1 },
             { "name": req.body.username2, "password": req.body.password2 }
          ]
      },function(err,result) {
          // logic in here
    
      })
    

    然后处理验证响应所需的任何逻辑,最明显的情况是,如果响应的长度不超过两个项目,则未找到其中一个选项。

    这是“用户名”当然应该有唯一约束的情况之一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-02
      • 2014-01-26
      • 2014-08-16
      • 2017-04-28
      • 2021-04-10
      • 2017-06-23
      相关资源
      最近更新 更多