Skip to content

Instantly share code, notes, and snippets.

@gaspaonrocks
Created May 15, 2017 21:01
Show Gist options
  • Save gaspaonrocks/c4f1610c2a13ed524e3a97a80a966982 to your computer and use it in GitHub Desktop.
Save gaspaonrocks/c4f1610c2a13ed524e3a97a80a966982 to your computer and use it in GitHub Desktop.
const mongoose = require('mongoose');
const express = require('express');
const faker = require('faker');
var app = express();
var userSchema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true
},
name: {
type: String
}
}, {
timestamps: true
});
var bookSchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true
},
category: String,
stock: Number,
_users: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
}, {
timestamps: true
});
var User = mongoose.model('User', userSchema);
var Book = mongoose.model('Book', bookSchema);
app.get('/users', function (req, res, next) {
User.find(function (err, users) {
if (err)
next(err);
else
res.json(users);
});
});
app.get('/users/new', function (req, res, next) {
var obj = {
name: faker.name.findName(),
email: faker.internet.email()
};
User.create(obj, function (err, user) {
if (err)
next(err);
else
res.json(user);
});
});
app.get('/books', function (req, res, next) {
Book.find(function (err, books) {
if (err)
next(err);
else
res.json(books);
});
});
app.get('/books/new', function (req, res, next) {
var obj = {
name: faker.name.title(),
category: faker.random.word(),
stock: parseInt(Math.random() * 10 + 1),
_users: []
};
Book.create(obj, function (err, book) {
if (err)
next(err);
else
res.json(book);
});
});
app.get('/books/:bookId', function (req, res, next) {
let books = [];
Book.find(function (err, collection) {
if (err) next(err);
else {
books = collection;
if (req.params.bookId >= books.length) {
res.send('There\'s no such book...');
} else res.json(books[req.params.bookId]);
}
});
});
app.get('/books/:bookId/newUser', function (req, res, next) {
let users = [];
User.find().lean().distinct('name', function (err, names) {
if (err) next(err);
else {
users = names;
res.json(users);
}
});
})
mongoose.connect('mongodb://localhost:27017/sample', function (err) {
if (err) throw err;
app.listen(8080, function () {
console.log('Listen started');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment