lundi 7 septembre 2020

How to use If statement and for loop in Nodejs?

I have two collections Developer and project. I want to assign more then one project to developer but i don't want to repeatedly assign any project.

/*@Submit assign project to developer */
exports.putDevAssign = (req, res, next) => {
    const {projectId, teamId} = req.body

    Team.findById(teamId)
    .then(result => {
        if(result.project.length == 0 ) {
            Team.findByIdAndUpdate(teamId, {$push: { project : projectId } }, { new: true }).populate('project')
                    .then(result => {
                        res.redirect('/Assigned-Developer/' + teamId)
                    })
                    .catch(err => console.log(err))
        } else {
            for(let i = 0; i < result.project.length; i++) {
                if( projectId == result.project[i] ) {  
                    req.flash('message', 'Already Assigned')
                    return res.redirect('/Assigned-Developer/' + teamId)
                } else {
                    console.log('hello')
                    Team.findByIdAndUpdate(teamId, {$push: { project : projectId } }, { new: true }).populate('project')
                    .then(result => {
                        return res.redirect('/Assigned-Developer/' + teamId)
                    })
                    .catch(err => console.log(err))
                }
            }
        }
    })
    .catch(err => console.log)
}

But in above code i can assign first project and it is neither repeatedly stored. but from second project it is stored repeatedly . I don't want this to happen. i want to assign only unique project. Help me with this silly error that i have made. Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire