I've got this piece of code that I seem to be getting in a bit of a muddle with. What it does is create users. Now, if a user has a company, then that company should be created along with the user and linked accordingly. If the company already exists, then it shouldn't be created and it shouldn't be attributed to the user.
First the code looks for a company, if it can't find one then one is created. Life is good. But if I were to add an else to my "if (!company)" check i would be duplicating the majority of my create user code. I also believe I can't check the company and then run the user creation synchronously as I would usually do in a different language. Hence i'm getting a little stuck..
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' })
})
})
}
})
}
EDIT#
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' })
})
}