Skip to content

Instantly share code, notes, and snippets.

@stmoerman
Created January 11, 2019 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stmoerman/ea974343488a2c2be8a1792d5d017e25 to your computer and use it in GitHub Desktop.
Save stmoerman/ea974343488a2c2be8a1792d5d017e25 to your computer and use it in GitHub Desktop.
const mongoose = require('mongoose');
mongoose.set('useFindAndModify', false);
mongoose.connect('mongodb://localhost:27017/mongo-demo', { useNewUrlParser: true })
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err));
const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [String],
date: { type: Date, default: Date.now },
isPublished: Boolean
});
const Course = mongoose.model('Courses', courseSchema);
async function createCourse() {
const course = new Course({
name: 'Angular Course',
author: 'Mosh',
tags: ['angular', 'frontend'],
isPublished: true
});
const result = await course.save();
console.log(result);
}
async function getCourses() {
const pageNumber = 2;
const pageSize = 10;
const courses = await Course
.find({ author: 'Mosh', isPublished: true })
.skip((pageNumber - 1) * pageSize)
.limit(pageSize)
.sort({ name: 1 })
.select({ name: 1, tags: 1 });
console.log(courses);
}
async function updateCourse(id) {
const course = await Course.findByIdAndUpdate(id, {
$set: {
author: 'Jason',
isPublished: false
}
}, { new: true });
console.log(course);
}
// updateCourse('5c3873f1b3ebc6256812ce81');
async function removeCourse(id) {
// const result = await Course.deleteMany({ _id: id })
const course = await Course.findByIdAndRemove(id);
console.log(course);
}
removeCourse('5c3873f1b3ebc6256812ce81');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment