'How do clean this code up? Node function taking multiple params with Mongoose
I am learning mongoose and I have ran into a "clean code" issue. The code works fine and is connected to another file containing my schema. The issue is the function call for "createNewApplicant."
It is getting messy really quick. I am trying to work towards creating an awesome job application / onboarding website for our talent team at my company.
Does anyone have any clean coding tips to shorten the function calls? I've thought of using an object but then I just pass the problem off to my object constructor and it doesn't really solve the issue.
Thank you so much for the time and consideration.
const mongoose = require('mongoose')
const Applicant = require('./Applicant')
const colors = require('colors')
//connecting to mongodb with mongoose
mongoose.connect(MONGOURI,
() => {
console.log('connected'.cyan)
},
e => console.error(e)
)
//a constructor function which creates a new applicant and stores it in our db
const createNewApplicant = async (fName, lName, eAddress, pNumber, hobbiesArray, addressObject) => {
try{
//phone number validation (checks length of phone number)
if (pNumber.length != 10){
console.log("incorrect phone number | shutting down function createNewApplicant".bgRed)
return
}
//we have to await because Applicant.create returns a promise
const applicant = await Applicant.create({
firstName: fName,
lastName: lName,
emailAddress: eAddress,
phoneNumber: pNumber,
hobbies: hobbiesArray,
address: addressObject
})
console.log("New Applicant Saved".yellow)
} catch (e) {
console.log(e.message)
}
}
//our function call to create a new applicant
createNewApplicant(
"Matthew",
"Igloo",
"[email protected]",
"9188585576",
["running", "skipping", "jumping"],
{ "city": "Tulsa", "state": "OK" }
)
Solution 1:[1]
So I would suggest you divide everything into smaller chunks
Eg. create multiple folder/files each doing a dedicated tasks..
Modelsfolder contains only the mongoose ModelsCorefolder contains the actual logic to connect to models (like find, create, update & delete etc) - make it generic i.e. eg. create fn should only accept an object and save it without validating or anythingControllerfolder which takes the input, create a format and send it to core for inserting, finding, update or delete- Also separate your validation and use libraries like joi or yup.. you can perform validation directly in route or in controller; I actually create middleware for this job
If you need more help on how to properly structure, you can chat up with me :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Saksham Khurana |
