How to check if that data already exist in the database during update (Mongoose And Express)

后端 未结 8 1877
灰色年华
灰色年华 2020-12-05 00:28

How to do validations before saving the edited data in mongoose?

For example, if sample.name already exists in the database, the user will receive a som

8条回答
  •  自闭症患者
    2020-12-05 00:54

    In addition to already posted examples, here is another approach using express-async-wrap and asynchronous functions (ES2017).

    Router

    router.put('/:id/settings/profile', wrap(async function (request, response, next) {
        const username = request.body.username
        const email = request.body.email
        const userWithEmail = await userService.findUserByEmail(email)
        if (userWithEmail) {
            return response.status(409).send({message: 'Email is already taken.'})
        }
        const userWithUsername = await userService.findUserByUsername(username)
        if (userWithUsername) {
            return response.status(409).send({message: 'Username is already taken.'})
        }
        const user = await userService.updateProfileSettings(userId, username, email)
        return response.status(200).json({user: user})
    }))
    

    UserService

    async function updateProfileSettings (userId, username, email) {
        try {
            return User.findOneAndUpdate({'_id': userId}, {
                $set: {
                    'username': username,
                    'auth.email': email
                }
            }, {new: true})
        } catch (error) {
            throw new Error(`Unable to update user with id "${userId}".`)
        }
    }
    
    async function findUserByEmail (email) {
        try {
            return User.findOne({'auth.email': email.toLowerCase()})
        } catch (error) {
            throw new Error(`Unable to connect to the database.`)
        }
    }
    
    async function findUserByUsername (username) {
        try {
            return User.findOne({'username': username})
        } catch (error) {
            throw new Error(`Unable to connect to the database.`)
        }
    }
    
    // other methods
    
    export default {
        updateProfileSettings,
        findUserByEmail,
        findUserByUsername,
    }
    

    Resources

    async function

    await

    express-async-wrap

提交回复
热议问题