Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何异步Mongoose控制器_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

Node.js 如何异步Mongoose控制器

Node.js 如何异步Mongoose控制器,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,正在尝试配置一个SignUp()控制器,当用户提供转介代码时,该控制器可以更新多个(单独的)用户帐户 基本流程: 验证系统中不存在电子邮件 找到与驾驶员的refCode匹配的驾驶员w/userID(FindOneAndUpdate) 如果找到:将每个用户的用户ID添加到其他用户[客户端]列表中 如果isRider 如果其中任何一个失败了。。。将特定错误返回给客户端/用户 这是行不通的。但本质上,这就是我想要实现的 试图将其配置为纯承诺,但没有运气。在我看来,大多数例子都不一样。。。也无法理解如

正在尝试配置一个
SignUp()
控制器,当用户提供转介代码时,该控制器可以更新多个(单独的)用户帐户

基本流程:

  • 验证系统中不存在电子邮件
  • 找到与驾驶员的
    refCode
    匹配的驾驶员w/
    userID
    (FindOneAndUpdate)
  • 如果找到:将每个用户的
    用户ID
    添加到其他用户
    [客户端]
    列表中
  • 如果
    isRider
  • 如果其中任何一个失败了。。。将特定错误返回给客户端/用户

  • 这是行不通的。但本质上,这就是我想要实现的

    试图将其配置为纯承诺,但没有运气。在我看来,大多数例子都不一样。。。也无法理解如何使用mongoose文档处理/抛出特定错误

    非常感谢任何人能伸出援手,谢谢


    更新: Ippi的回答帮助了一吨Thx

    这就成功了。记住从
    返回
    null
    。然后()在
    req.login
    之后返回
    null
    ,以避免出现警告-感谢您提供有关如何改进此功能的任何提示-Thx

      const createUser = (foundUser) => {
        if (foundUser) { throw new Error('This e-mail address already exist.'); }
        if (!req.body.isRider) { return newUser.save(); }
        return User.findOneAndUpdate({ 'profile.userID': req.body.refCode.toLowerCase() }, { $push: { clients: newUser.profile.userID }}).exec()
          .then((driver) => {
            if (!driver) { throw new Error('We can\'t find your driver.'); }
            newUser.clients = [req.body.refCode];
            return newUser.save();
          })
          .catch(() => { throw new Error('There was a database error.'); });
      };
    
      User.findOne({ email: req.body.email }).exec()
        .then(createUser)
        .then((user) => {
          if (user.profile) {
            req.logIn(user, (loginErr) => {
              if (loginErr) return res.sendStatus(401);
              return res.status(200).send({ profile: user.profile, clients: user.clients });
            });
          } else { res.status(409); }
          return null;
        })
        .catch((err) => { return res.status(409).send(err.message); });
    

    我会这样做的。我懒得尝试express或登录(您需要将
    console.log
    替换为
    res.status().json()
    ),我可能在驱动程序的逻辑上犯了一些其他错误。但除此之外,我用当地的mongo进行了测试,它可能有效,如果没有其他东西的话,它会更简洁一点

    let updateUser = user => {
      if (user){ throw new Error("USER_EXIST"); }
      if (!req.body.isRider) { return newUser.save() }
      return User.findOneAndUpdate({ 'profile.userID': req.body.refCode },{ $push: { clients: newUser.profile.userID }}).exec()
        .then(driver => {
          if (!driver) { throw new Error("NO_DRIVER");}
          newUser.clients.push(req.body.refCode);
          return newUser.save();
        });
    }
    
    User.findOne({ email: req.body.email }).exec()
      .then(updateUser)
      .then(req.logIn) // newUser.save() response is passed in as is (I have not tested this line.)
      .then( ()=>{ return console.log('profile', newUser.profile);  })
      .catch( Error,  err => {
        if (err.message == "USER_EXISTS") return console.log ("This e-mail address already exist." );
        if (err.message == "NO_DRIVER") return console.log ("We can't find your driver." );
          throw err;
      });
    
    值得记住的是:

    • 回调调用或res.send应始终位于最后一个then/catch中。在链中间调用res.send会导致麻烦

      • 我会这样做。我懒得尝试express或登录(您需要将
        console.log
        替换为
        res.status().json()
        ),我可能在驱动程序的逻辑上犯了一些其他错误。但除此之外,我用当地的mongo进行了测试,它可能有效,如果没有其他东西的话,它会更简洁一点

        let updateUser = user => {
          if (user){ throw new Error("USER_EXIST"); }
          if (!req.body.isRider) { return newUser.save() }
          return User.findOneAndUpdate({ 'profile.userID': req.body.refCode },{ $push: { clients: newUser.profile.userID }}).exec()
            .then(driver => {
              if (!driver) { throw new Error("NO_DRIVER");}
              newUser.clients.push(req.body.refCode);
              return newUser.save();
            });
        }
        
        User.findOne({ email: req.body.email }).exec()
          .then(updateUser)
          .then(req.logIn) // newUser.save() response is passed in as is (I have not tested this line.)
          .then( ()=>{ return console.log('profile', newUser.profile);  })
          .catch( Error,  err => {
            if (err.message == "USER_EXISTS") return console.log ("This e-mail address already exist." );
            if (err.message == "NO_DRIVER") return console.log ("We can't find your driver." );
              throw err;
          });
        
        值得记住的是:

        • 回调调用或res.send应始终位于最后一个then/catch中。在链中间调用res.send会导致麻烦

        .then((err,foundDriver)
        有了承诺,你永远不会传递错误。相反,在你的承诺链中,你使用的是
        .then(…).catch(err=>{…})
        。在何种程度上,尽量不要将回调和承诺混为一谈。这会让你的世界变得更容易。
        。(err,foundDriver)
        对于承诺,您永远不会传递错误。而是使用承诺链中的最后一个
        。然后(…).catch(err=>{…})
        。在何种程度上,尽量不要将回调和承诺混为一谈。这将使您的世界变得更加简单。+1。尽管我仍然执行第一个findOne查询以获得承诺,但要链接结果,从
        调用的函数中删除err参数。然后()
        ,使用
        save()返回的承诺
        (两次)并使用.catch来处理错误。我认为用一个新的承诺来包装整个事情是胡说八道的!(抱歉)这正是我想要做的,将整个事情设置为一个链接承诺…但是,我使用的系统不希望返回承诺(控制器:,反应操作:)+尽管我仍然要执行第一个findOne查询以获得承诺,链接结果,从
        调用的函数中删除err参数。然后()
        ,使用
        save()
        返回的承诺(两次)并使用.catch来处理错误。我认为用一个新的承诺来包装整个过程是毫无意义的!(抱歉)这正是我想要做的,将整个事情设置为一个链式承诺…但是,我使用的系统不希望返回承诺(控制器:,反应动作:)哦,我使用蓝鸟,不确定它如何发挥;
        mongoose.promise=require('bluebird'))
        噢,我用的是蓝鸟,不确定它在游戏中的作用;
        mongoose.Promise=require('bluebird');
        let updateUser = user => {
          if (user){ throw new Error("USER_EXIST"); }
          if (!req.body.isRider) { return newUser.save() }
          return User.findOneAndUpdate({ 'profile.userID': req.body.refCode },{ $push: { clients: newUser.profile.userID }}).exec()
            .then(driver => {
              if (!driver) { throw new Error("NO_DRIVER");}
              newUser.clients.push(req.body.refCode);
              return newUser.save();
            });
        }
        
        User.findOne({ email: req.body.email }).exec()
          .then(updateUser)
          .then(req.logIn) // newUser.save() response is passed in as is (I have not tested this line.)
          .then( ()=>{ return console.log('profile', newUser.profile);  })
          .catch( Error,  err => {
            if (err.message == "USER_EXISTS") return console.log ("This e-mail address already exist." );
            if (err.message == "NO_DRIVER") return console.log ("We can't find your driver." );
              throw err;
          });