Created
November 29, 2019 04:08
-
-
Save harrisonmalone/31a3587faf67d481474d1e74811534d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const express = require('express') | |
| const mongoose = require('mongoose') | |
| const User = require('./models/User') | |
| const { celebrate, Joi, errors } = require('celebrate'); | |
| 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 validate = celebrate({ | |
| body: Joi.object().keys({ | |
| username: Joi.string(), | |
| password: Joi.string() | |
| }) | |
| }) | |
| app.use(validate) | |
| app.use(errors()) | |
| app.post('/create', 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')) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "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": { | |
| "celebrate": "^10.1.0", | |
| "express": "^4.17.1", | |
| "mongoose": "^5.7.12" | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const mongoose = require('mongoose') | |
| const Schema = mongoose.Schema | |
| const myValidator = (username) => { | |
| return username === "harrison" | |
| } | |
| const userSchema = new Schema({ | |
| username: { | |
| type: String, | |
| validate: [myValidator, "name must be harrison error"] | |
| }, | |
| 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