Node JS Mongoose 异步回调

好黄蛋

我有这段代码,我似乎有点糊涂了。它所做的是创建用户。现在,如果用户拥有公司,则该公司应与用户一起创建并相应地链接。如果公司已经存在,则不应创建它,也不应将其归因于用户。

首先,代码查找一家公司,如果找不到,则创建一家公司。生活很好。但是,如果我要在“if (!company)”检查中添加一个 else,我将复制大部分创建用户代码。我也相信我无法检查公司然后同步运行用户创建,就像我通常用不同的语言所做的那样。因此我有点卡住了..

module.exports = {
  postUsers: (req, res) => {
    'use strict'
    Company.findOne({name: req.body.company}, (err, company) => {
      if (err) {
        Logger.error(err)
        return res.send(500, err)
      }
      if (!company) {
        // only attribute a company if one doesn't exist
        // don't want users to assign themselves to existing companies automatically
        // need approval in place from an existing company member
        let newCompanyToAdd = new Company({
          name: req.body.company
        })
        newCompanyToAdd.save(err => {
          if (err) {
            Logger.error(err)
            return res.send(500, err)
          }
          let user = new User({
            username: req.body.username,
            password: req.body.password,
            firstname: req.body.firstname,
            lastname: req.body.lastname,
            company: newCompanyToAdd.id
          })
          user.save(err => {
            if (err) {
              return res.send(500, err)
            }
            res.status(200).json({ message: 'New User Added' })
          })
        })
      }
    })
  }

编辑#

  postUsers: (req, res) => {
    'use strict'
    let user = new User({
      username: req.body.username,
      password: req.body.password,
      firstname: req.body.firstname,
      lastname: req.body.lastname
    })
    Company.findOne({name: req.body.company}, (err, company) => {
      if (err) {
        Logger.error(err)
        return res.send(500, err)
      }
      if (!company && req.name.company !== undefined) {
        // only attribute a company if one doesn't exist
        // don't want users to assign themselves to existing companies automatically
        // need approval in place from an existing company member
        let newCompanyToAdd = new Company({
          name: req.body.company
        })
        newCompanyToAdd.save(err => {
          if (err) {
            Logger.error(err)
            return res.send(500, err)
          }
          user.company = newCompanyToAdd._id
        })
      }
    })
    user.save(err => {
      if (err) {
        return res.send(500, err)
      }
      res.status(200).json({ message: 'New User Added' })
    })
  }
詹姆斯·奎克

我不完全确定我理解总体目标。但似乎您担心复制添加用户代码,因为无论公司是否已经存在,您都需要添加用户。有什么理由不能先保存用户,然后在回调中,有条件地创建公司吗?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章