0

I have to login with phonenumber (containing coutry code like '380325632589') Here 380 is country code and rest is phone number. But current database saves country code and phone number separately. So I can't find it by normal find query.

var UserSchema = new Schema({
  username: {
    type: String,
    trim: true
  },
  email: {
    type: String,
    trim: true
  },
  password: {
    type: String
  },
  phone_number: {
    type: String
  },
  country_code: {
    type: String
  }
});

And user can login should login via email or phonenumber so I am going to use a input field as phoneOremail.

User.findOne(
  {
    $or: [
      { phone_number: req.body.phoneOremail },
      { email: req.body.phoneOremail }
    ]
  },
  function(err, user) {}
);

But it doesn't work because country_code didn't considered. I don't want to create new field that containing countrycode only for this. Thanks.

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
Nomura Nori
  • 4,689
  • 8
  • 47
  • 85
  • Possible dupe https://stackoverflow.com/questions/4442453/mongodb-query-condition-on-comparing-2-fields. Same concept as in the marked duplicate, using `$expr` as `User.findOne({$or:[ {$expr:{$eq:[ {$concat: ["$country_code", "$phone_number"]}, req.body.phoneOremail]}}, {'email': req.body.phoneOremail}]}, function(err, user) { });` – chridam Mar 12 '18 at 19:32
  • But I got this error. MongoError: unknown top level operator: $expr – Nomura Nori Mar 12 '18 at 19:35
  • `$expr` is only supported in MongoDB 3.6+ – chridam Mar 12 '18 at 19:37
  • I am using Mongolab and it only support v3.4.13, how to solve it – Nomura Nori Mar 12 '18 at 19:41
  • If your MongoDB version is not 3.6, you could try the other alternative using `$redact` as `User.aggregate([ { "$redact": { "$cond": [ { "$or": [ {$eq:[ {$concat: ["$country_code", "$phone_number"]}, req.body.phoneOremail]}, {$eq:["$email", req.body.phoneOremail] } ] }, "$$KEEP", "$$PRUNE" ] } } ]).exec(callback)` Explanations also in one of the answers in https://stackoverflow.com/questions/4442453/mongodb-query-condition-on-comparing-2-fields – chridam Mar 12 '18 at 19:43
  • sorry, it doesn't work... – Nomura Nori Mar 12 '18 at 19:46

0 Answers0