2017-10-16 105 views
0

嘿,我試圖在express函數內改變Mongoose查詢函數以外的變量值。下面是我的代碼示例:如何在Mongoose函數中進行變量更改

//Register 
router.post('/register', (req, res, next) => { 
    let newUser = new User({ 
    name: req.body.name, 
    email: req.body.email, 
    username: req.body.username, 
    password: req.body.password 
    }); 

    var exists; 

    User.findOne({ 
      email: req.body.email 
     }, function (err, existingUser) { 

      if (existingUser) { 
       console.log('Email exists'); 
       exists = true; 
      } 
     }); 
    User.findOne({ 
      username: req.body.username 
     }, function (err, existingUser) { 

      if (existingUser) { 
       console.log('Username exists'); 
       exists = true; 
      } 
     }); 

    console.log(exists); 
    if (exists == true) { 
    res.json({ 
     success: false, 
     msg: 'Email or username is already registered' 
    }) 
    } 
}); 

變量「存在」是即使ExistingUser條件爲真還是不確定的。如何對變量進行更改或者是更好的方法?

+0

Mongoose查詢是異步的。 – TGrif

+0

@TGrif無論如何我可以解決這個問題以達到我的目標? – Axelotl

+0

是的,您可以使用[此處](https://stackoverflow.com/a/6181967/5156280)中所述的流量控制庫。 – TGrif

回答

0
`//Register 
router.post('/register', (req, res, next) => { 
    let newUser = new User({ 
    name: req.body.name, 
    email: req.body.email, 
    username: req.body.username, 
    password: req.body.password 
    }); 

    var exists; 

    User.findOne({ 
    '$or': [{ 
     email: req.body.email 
    }, { 
     username: req.body.username 
    }] 
    }, function (err, existingUser) { 
    if (existingUser) { 
     console.log('Email exists'); 
     exists = true; 
    } 
    console.log(exists); 
    if (exists == true) { 
     res.json({ 
     success: false, 
     msg: 'Email or username is already registered' 
     }) 
    } 
    }); 

})` 

試試上面的代碼。

相關問題