简体   繁体   中英

how to multiple model can use single api in node.js

i create login api for admin, principle, teacher, student all model for single api but not supported array of findOne() function.

i am trying array through and promise.

router.get('/login', function(req, res){

    var anc = [admin, principle, teacher, student];

    // Promise.all([
    //     admin.findOne({email: req.body.email}),
    //     student.findOne({email: req.body.email})
    // ]).then(function(data){
    //     res.send(data)
    // }).catch(function(err){
    //     res.send(err);
    // })

    //this is not working proper 
    // if find email in admin then show admin data and student = null.

    anc.findOne({ email: req.body.email}, function(err, data){
        // console.log(data);
        //  res.send(data);

        if(err){
            next(err);
        } else {
            if(data != null && bcrypt.compareSync(req.body.password, data.password)){

                const token = jwt.sign({data}, 'abcde', { expiresIn: '1h'});
                res.json({status: "success", message: "user found!!", data: {userrole: data.userrole, token: token}});
            } else{
                res.json({status:"error", message: "Invalid email/password!!!", data:null});
            }
        }
    });
});

Looks like your anc.findOne is an error first callback style pattern, so it will not work with Promise.all since it expects an array of promises.

If you want to use Promise.all , then you need to turn both of your database calls ( admin.findOne & student.findOne ) to promises.

For example:

// let's assume `admin.findOne` uses an error first callback style
function adminFindOneAsPromise(params) {
  return new Promise(function(resolve, reject) {
    admin.findOne({ email: params.email }, function(err, data) {
      if (err) {
        reject(err)
        return
      }
      resolve(data)
    })
  })
}
function studentFindOneAsPromise(params) {
  // same idea as above
}

Then you could use these new functions in your Promise.all :

router.get('/login', function(req, res) {
  Promise.all([
    adminFindOneAsPromise({ email: req.body.email }),
    studentFindOneAsPromise({ email: req.body.email })
  ])
  .then(function(result) {
    // `result` will be an array of values that got returned
    // as a result of calling both 
    // `adminFindOneAsPromise` & `studentFindOneAsPromise`
    const [adminResult, studentResult] = result

    // ...

    res.json({ status: "success", ... })
  })
  .catch(function(error) {
    // handle your error appropriately
    res.json({ status: "error", ... })
  })
})

Also, one thing that I want to point out is that this will not work:

router.get('/login', function(req, res) {
  var anc = [admin, principle, teacher, student]

  // `anc` is an array, and you can't access 
  // its content with the `dot` notation
  anc.findOne(...) // is wrong

  // if you want to use the `admin`-related calls,
  // you need to use an index, so it should be
  anc[0].findOne(...)
})

However, I'd advise to not put these in an array because from what it looks like there's no reason for it. Just simply use:

router.get('/login', function(req, res) {
  admin.findOne(...)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM