Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.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
Javascript 如何在mongoose函数的if/else块中来回跳转?_Javascript_Node.js_If Statement_Mongoose_Promise - Fatal编程技术网

Javascript 如何在mongoose函数的if/else块中来回跳转?

Javascript 如何在mongoose函数的if/else块中来回跳转?,javascript,node.js,if-statement,mongoose,promise,Javascript,Node.js,If Statement,Mongoose,Promise,如何在mongoose函数的if/else块中来回跳转? 我的意思是,当我的用户已经存在时,检查if块,如果我的用户在db中不存在,则转到else块并保存用户,然后返回if块,在保存用户后,我不想将if块复制并粘贴到else块 代码: User.findById(msg.chat.id) .then((doc) => { if (doc) { console.log(doc.name); // to here } else { console.

如何在mongoose函数的if/else块中来回跳转?
我的意思是,当我的用户已经存在时,检查if块,如果我的用户在db中不存在,则转到else块并保存用户,然后返回if块,在保存用户后,我不想将if块复制并粘贴到else块

代码:

User.findById(msg.chat.id)
  .then((doc) => {
    if (doc) {
      console.log(doc.name);  // to here
    } else {
      console.log('Empty');  //jump from here
    }
  }).catch((err) => {
    if (err) {
      console.log(err);
    }
  });
你是说像这样

使用回调时,我们保证在使用文档时保存文档

与save receives方法一起使用的回调


只需将公共部分从
if/else
块中删除。您能用我的示例进行编辑吗,我的意思是我想在else块中保存用户,然后回到ifWell,这是一个完全不同的问题。我建议您编辑您的示例,因为我和@FirasOmrane都不理解其他内容。您应该真正编辑您的代码示例,因为它非常混乱,对您提出的实际问题毫无帮助。阅读OP的评论后,我想他们实际上想在
else
块中完成某项操作后重新运行
findById
,而这实际上并不仅仅是
控制台.log
的事情。我的意思是当我的用户已经存在时,检查if块,如果我的用户不在db中,则转到else块并保存用户,然后返回if,保存后,我不想将if块复制并粘贴到else块users@SedricHeidarizarei我修改了它以适应您的请求
//在这里,您可以对每个用户编码您想做的事情
他们必须再次
findById
,您的示例没有解释如何做,这是问题的关键所在。@SedricHeidarizarei我修改了代码,以便对其进行更深入的开发和解释。不客气。
  function workAfterSaving(result) {
    console.log(result.tok);
  }

  User.findById(msg.chat.id)
    .then((doc) => {
      if (!doc) {
        // we will add the user
        kitty.save()
          .then((obj) => {
            workAfterSaving(obj);
          }).catch((err) => {
            if (err) {
              console.log(err);
            }
          });
        return;
      }

      // here we will use the same function with the found user.
      workAfterSaving(doc);
    }).catch((err) => {
      if (err) {
        console.log(err);
      }
    });
});