Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Last active December 3, 2019 23:36
Show Gist options
  • Select an option

  • Save harrisonmalone/e7977ffd3b3f809a29a6e2bac2153036 to your computer and use it in GitHub Desktop.

Select an option

Save harrisonmalone/e7977ffd3b3f809a29a6e2bac2153036 to your computer and use it in GitHub Desktop.
const express = require('express')
const mongoose = require('mongoose')
const User = require('./User')
const Joi = require('@hapi/joi')
const app = express()
const dbOptions = { useNewUrlParser: true, useUnifiedTopology: true }
mongoose.connect('mongodb://localhost:27017/validation-testing', dbOptions, (err) => {
if (err) {
console.log('db down ❌')
} else {
console.log('db up ✅')
}
})
app.use(express.json())
const schema = Joi.object().keys({
username: Joi.string(),
password: Joi.string()
})
const validate = (req, res, next) => {
const result = schema.validate(req.body)
if (result.error) {
res.status(500).send(result.error.details[0].message)
} else {
next()
}
}
app.post('/create', validate, async (req, res) => {
try {
const user = new User(req.body)
res.send(await user.save())
} catch(err) {
res.status(500).send(err)
}
})
app.listen(5000, () => console.log('listening on port 5000'))
{
"name": "mongoose-validation",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@hapi/joi": "^16.1.8",
"celebrate": "^10.1.0",
"express": "^4.17.1",
"mongoose": "^5.7.12"
}
}
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const myUniqueValidator = async (username) => {
const doc = await User.findOne({username: username})
if (doc) {
return false
} else {
return true
}
}
const userSchema = new Schema({
username: {
type: String,
required: true,
validate: [myUniqueValidator, "username must be unique"]
},
password: String
})
const User = mongoose.model('User', userSchema)
module.exports = User
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment