Skip to content

Instantly share code, notes, and snippets.

@sanjivyash
Last active September 5, 2020 10:57
Show Gist options
  • Save sanjivyash/32b24d818333bf859029734350f0c14a to your computer and use it in GitHub Desktop.
Save sanjivyash/32b24d818333bf859029734350f0c14a to your computer and use it in GitHub Desktop.
A starter file with various functions and properties of the mongoose library
const mongoose = require('mongoose');
const validator = require('validator');
const log = console.log;
mongoose.connect('mongodb://127.0.0.1:27017/tasty-momos', {
useNewUrlParser: true,
useCreateIndex: true
});
const User = mongoose.model('User', {
name: { // validation
type: String,
trim: true,
required: true,
},
email: {
type: String,
lowercase: true,
trim: true,
validate(value) {
if(!validator.isEmail(value)) {
throw new Error('Invalid Email Address');
}
}
},
password: {
type: String,
required: true,
minlength: 7,
validate(value) {
if(value.toLowerCase.includes('password')){
throw new Error('Set a stronger password');
}
}
},
age: {
type: Number,
default: 0,
validate(value) {
if(value < 0) {
throw new Error('Age needs to be positive');
}
}
}
});
const me = new User({
name: 'Yash',
email: 'lolwa@gmail.com',
password: ' pleasesavemepyu',
age: 20
});
me.save()
.then(me => {
log(me);
// do whatever you want
})
.catch(err => log(err));
const Task = mongoose.model('Task', {
description: {
type: String,
trim: true,
required: true
},
completed: {
type: Boolean,
default: False
}
});
const clean = new Task({
description: 'Clean the house',
completed: false
});
clean.save()
.then(clean => {
log(clean)
// do whatever you want
})
.catch(err => log(err));
// remember, Mongoose stores models in lowercase plurals
// User is stored in users, Task is stored in tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment