简体   繁体   中英

mongoose find multiple documents

I have one basic User schema

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

Now I want to implement dual login feature,

  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) {
      ....

I want to whether there is simple way to find those two user information in one User.find() function?

You just use $or . Also your use of $and is redundant here:

  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

  })

And then process whatever logic you need to validate the response, with the clearest case being that if the response is not at least two items long then one of the selections was not found.

This is one of those cases where of course "username" should have a unique constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM