Skip to content

Instantly share code, notes, and snippets.

@gaspaonrocks
Created May 15, 2017 21:01
Show Gist options
  • Select an option

  • Save gaspaonrocks/c4f1610c2a13ed524e3a97a80a966982 to your computer and use it in GitHub Desktop.

Select an option

Save gaspaonrocks/c4f1610c2a13ed524e3a97a80a966982 to your computer and use it in GitHub Desktop.

Revisions

  1. @gaspaonrocksBis gaspaonrocksBis created this gist May 15, 2017.
    116 changes: 116 additions & 0 deletions dbtest.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,116 @@
    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');
    });
    });