Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var mongoose = require('mongoose');
- var async = require('async');
- mongoose.connect("mongodb://localhost/so_quotes");
- // ===================================================
- // Quote schema
- var QuoteSchema = new mongoose.Schema({
- quote: String
- });
- // Finds a random quote based on how many there are in the collection
- QuoteSchema.statics.random = function(cb) {
- this.count(function(err, count) {
- if (err) return cb(err);
- var rand = Math.floor(Math.random() * count);
- this.findOne().skip(rand).exec(cb);
- }.bind(this));
- };
- // Finds the 'next quote'
- QuoteSchema.methods.next = function(cb) {
- var model = this.model("Quote");
- model.findOne().where('_id').gt(this._id).exec(function(err, quote) {
- if (err) throw err;
- if (quote) {
- cb(null, quote);
- } else {
- // If quote is null, we've wrapped around.
- model.findOne(cb);
- }
- });
- };
- var Quote = mongoose.model("Quote", QuoteSchema);
- // ===================================================
- // User schema
- var UserSchema = new mongoose.Schema({
- user: String,
- lastQuote: { type: mongoose.Schema.Types.ObjectId, ref: 'Quote' }
- });
- var User = mongoose.model("User", UserSchema);
- // ===================================================
- // Clear out old data and re-initialize each time the program runs
- function reset(callback) {
- async.parallel([
- Quote.remove.bind(Quote),
- User.remove.bind(User)
- ], function(err) {
- if (err) throw err;
- callback();
- });
- }
- // ===================================================
- // Seed the database with initial data.
- function seed(callback) {
- quotes = [
- "Chuck Norris counted to infinity - twice.",
- "When the Boogeyman goes to sleep every night he checks his closet for Chuck Norris.",
- "Chuck Norris has already been to Mars; that's why there are no signs of life there.",
- "The chief export of Chuck Norris is pain.",
- "There is no chin behind Chuck Norris' beard. There is only another fist.",
- "When Chuck Norris had surgery, the anesthesia was applied to the doctors.",
- "Chuck Norris is what Willis was talking about.",
- "If you have five dollars and Chuck Norris has five dollars, Chuck Norris has more money than you.",
- "Ironically, Chuck Norris' idden talent is invisibility."
- ];
- async.parallel([
- function(cb) {
- async.forEachSeries(quotes, function(quote, eachCallback) {
- var q = new Quote({quote: quote});
- q.save(eachCallback);
- }, cb);
- },
- function(cb) {
- var user = new User({user: "JohnDoe"});
- user.save(cb);
- }
- ], function(err, results) {
- if (err) throw err;
- callback();
- })
- }
- module.exports = {
- Quote: Quote,
- User: User,
- reset: reset,
- seed: seed
- };
Add Comment
Please, Sign In to add comment