【问题标题】:What is the best way to query this in mongoose?在猫鼬中查询这个的最佳方法是什么?
【发布时间】:2012-07-20 13:02:40
【问题描述】:

我有 2 个模型用户和 user_verifications。用户有用户名和电子邮件,user_verification 也有。

在向用户插入数据之前,我先在 user_verification 中插入数据。 所以,我想知道用户名或电子邮件是否已经注册。

我就是这样做的。

User.count({email: email}, function(err, count) {
   if (count > 0) return false;
   else User.count({username: username}, function(err, count) {
       if (count > 0) return false;
     else UserVerification.count({email: email}, function(err, count) {
        if (count > 0) return false;
        else UserVerification.count({username: username}, function(err, count) {
            if (count > 0) return false;
            return true;
        });
     });
  });
});

但这有点烦人,因为我必须一遍又一遍地做同样的事情。有更好的方法吗?

谢谢。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    可能有帮助的一件事是使用 $or 查询,这样您就不必对同一个集合进行两个单独的查询。

    User.count({ $or : [ { email : email } , { username : username } ] }, 
        function () {...} );
    

    您可能还想使用异步库(例如 async),以便可以并行进行这些调用,因为它们不相互依赖。

    async.parallel({
       user:  function(cb) { 
           User.count({$or : [ {email:email}, {username:username}]}, cb);
       },
    
       verification: function(cb) {
           UserVerification.count({$or : [{email:email}, {username:username}]}, cb);
       }
    },
    function (err, results) {
       return !(results.user > 0 || results.verification > 0)
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多