如何使用promises链接mongoose查询?

时间:2017-03-02 04:01:45

标签: javascript node.js mongodb mongoose

嘿伙计们,我是初学者,而且我正在处理我的第一个快速和mongo应用程序,但我不知道如何使用javascript承诺链接查询以使其作为同步查询工作。 请帮我链接这些mongoose查询。

 /* POST Register User  */
 router.post('/register',function(req,res,next){

let user = req.body;
//checking for empty field in a form
for(let key in user){
   if(user[key] === ""){
      return next(mid.error("All fields are required to fill"));
   }
}

User.findOne({username:user.username})
.exec(function(err,user){
    if(err){
        return next(mid.error("Something went wrong"));
    }
    if(user){
        return next(mid.error("Username already exist"));
    }
});

User.findOne({email:user.email})
    .exec(function(err,user){
        if(err){
           return next(mid.error("Something went wrong"));
        }
        if(user){
           return next(mid.error("Email already exist"));
        }
    });

  //matching password 
  if(user.password !== user.confirm){
     return next(mid.error("Password not matched.Try again !"));
  }

  //save data in object
  let userData = {
     username : user.username,
     email    : user.email,
     password : user.password
   };

  //save data in database

  User.create(userData,function(err,user){
   if(err){
      return next(mid.error("Something went wrong.Try again !!!"));
    } else {
       req.session.userID = user._id;
       return res.redirect('/home');
    } 

 });

 });

3 个答案:

答案 0 :(得分:1)

/* POST Register User  */
router.post('/register',function(req,res,next){

let user = req.body;
let validError = [];
//checking for empty field in a form
for(let key in user){
    if(user[key] === ""){
        return next(mid.error("All fields are required to fill"));
    }
}

let findUserName = () => {
 return new Promise(function(resolve,reject){
    User.findOne({username:user.username})
      .exec(function(err,user){
        if(err){
          validError.push("Something went wrong");
        }
        if(user){
          validError.push("Username already exist");
        }
          return resolve();
    });
});
}


let findUserEmail = () => {
  return new Promise(function(resolve,reject){
      User.findOne({email:user.email})
        .exec(function(err,user){
          if(err){
            validError.push("Something went wrong");
          }
          if(user){
            validError.push("Email already exist");
          }
            return resolve();
      });
  });
 }

let isPasswordMatch = () => {
  return new Promise(function(resolve,reject){
      if(user.password !== user.confirm){
        validError.push("Password not matched");
      }
      return resolve();
 });
}

 findUserName().then(findUserEmail).then(isPasswordMatch).then(() => {

   if(validError.length == 0){
       //save data in object
       let userData = {
         username : user.username,
         email    : user.email,
         password : user.password
       };

       //save data in database

       User.create(userData,function(err,user){
         if(err){
           return next(mid.error("Something went wrong.Try again !!!"));
         } else {
           req.session.userID = user._id;
           return res.redirect('/home');
         }

      });

    }else{
      return next(mid.error(validError[0]));
    }

  });


 }); 

终于做到了!谢谢你们所有人

答案 1 :(得分:0)

承诺链条并不总是有利的,你必须分析链条是否会支持你的情况或者会恶化你的问题。在您的情况下,如果任何查询{findByName,findByEmail,Create}失败,您必须从那里返回。如果您使用promise链接进行尝试,那么如果上述任何操作都失败,那么下一个 .then or .catch 链式承诺将会连续执行。因此,在我看来,您所需要的只是 Promise.all 。下面我提供了jsfiddle代码的链接。为了您的理解,我已经给出了链接方法,但不建议这样做。跟Promise.all一起去吧

with Promise.all

with promises chaining

答案 2 :(得分:0)

使用Rx和mongoose-observables:)

var Rx = require('rx');
var observables = require('mongoose-observables');

/* get public header data, list of collections and projects */

router.get("/header", function(req, res) {
  let articleTitle = observables.finder.find(Articles, '{}', ['title'], null);
  let collectionTitle = observables.finder.find(Collections, '{}', ['title'], null);

  Rx.Observable.forkJoin([articleTitle, collectionTitle])
    .subscribe(
      (docs) => res.json(docs),
      (err) => console.error(err)
    );

});

https://www.npmjs.com/package/mongoose-observables

的更多示例