diff --git a/examples/README.md b/examples/README.md deleted file mode 100644 index 8511ee44434..00000000000 --- a/examples/README.md +++ /dev/null @@ -1,41 +0,0 @@ -# Examples - -This directory contains runnable sample mongoose programs. - -To run: - -* first install [Node.js](http://nodejs.org/) -* from the root of the project, execute `npm install -d` -* in the example directory, run `npm install -d` -* from the command line, execute: `node example.js`, replacing "example.js" with the name of a program. - -Goal is to show: - -* ~~global schemas~~ -* ~~GeoJSON schemas / use (with crs)~~ -* text search (once MongoDB removes the "Experimental/beta" label) -* ~~lean queries~~ -* ~~statics~~ -* methods and statics on subdocs -* custom types -* ~~querybuilder~~ -* ~~promises~~ -* accessing driver collection, db -* ~~connecting to replica sets~~ -* connecting to sharded clusters -* enabling a fail fast mode -* on the fly schemas -* storing files -* ~~map reduce~~ -* ~~aggregation~~ -* advanced hooks -* using $elemMatch to return a subset of an array -* query casting -* upserts -* pagination -* express + mongoose session handling -* ~~group by (use aggregation)~~ -* authentication -* schema migration techniques -* converting documents to plain objects (show transforms) -* how to $unset diff --git a/examples/aggregate/aggregate.js b/examples/aggregate/aggregate.js deleted file mode 100644 index 24f172210f0..00000000000 --- a/examples/aggregate/aggregate.js +++ /dev/null @@ -1,105 +0,0 @@ - -// import async to make control flow simplier -'use strict'; - -const async = require('async'); - -// import the rest of the normal stuff -const mongoose = require('../../lib'); - -require('./person.js')(); - -const Person = mongoose.model('Person'); - -// define some dummy data -const data = [ - { - name: 'bill', - age: 25, - birthday: new Date().setFullYear((new Date().getFullYear() - 25)), - gender: 'Male', - likes: ['movies', 'games', 'dogs'] - }, - { - name: 'mary', - age: 30, - birthday: new Date().setFullYear((new Date().getFullYear() - 30)), - gender: 'Female', - likes: ['movies', 'birds', 'cats'] - }, - { - name: 'bob', - age: 21, - birthday: new Date().setFullYear((new Date().getFullYear() - 21)), - gender: 'Male', - likes: ['tv', 'games', 'rabbits'] - }, - { - name: 'lilly', - age: 26, - birthday: new Date().setFullYear((new Date().getFullYear() - 26)), - gender: 'Female', - likes: ['books', 'cats', 'dogs'] - }, - { - name: 'alucard', - age: 1000, - birthday: new Date().setFullYear((new Date().getFullYear() - 1000)), - gender: 'Male', - likes: ['glasses', 'wine', 'the night'] - } -]; - - -mongoose.connect('mongodb://127.0.0.1/persons', function(err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function(item, cb) { - Person.create(item, cb); - }, function(err) { - if (err) { - // handle error - } - - // run an aggregate query that will get all of the people who like a given - // item. To see the full documentation on ways to use the aggregate - // framework, see http://www.mongodb.com/docs/manual/core/aggregation/ - Person.aggregate( - // select the fields we want to deal with - { $project: { name: 1, likes: 1 } }, - // unwind 'likes', which will create a document for each like - { $unwind: '$likes' }, - // group everything by the like and then add each name with that like to - // the set for the like - { $group: { - _id: { likes: '$likes' }, - likers: { $addToSet: '$name' } - } }, - function(err, result) { - if (err) throw err; - console.log(result); - /* [ - { _id: { likes: 'the night' }, likers: [ 'alucard' ] }, - { _id: { likes: 'wine' }, likers: [ 'alucard' ] }, - { _id: { likes: 'books' }, likers: [ 'lilly' ] }, - { _id: { likes: 'glasses' }, likers: [ 'alucard' ] }, - { _id: { likes: 'birds' }, likers: [ 'mary' ] }, - { _id: { likes: 'rabbits' }, likers: [ 'bob' ] }, - { _id: { likes: 'cats' }, likers: [ 'lilly', 'mary' ] }, - { _id: { likes: 'dogs' }, likers: [ 'lilly', 'bill' ] }, - { _id: { likes: 'tv' }, likers: [ 'bob' ] }, - { _id: { likes: 'games' }, likers: [ 'bob', 'bill' ] }, - { _id: { likes: 'movies' }, likers: [ 'mary', 'bill' ] } - ] */ - - cleanup(); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/examples/aggregate/package.json b/examples/aggregate/package.json deleted file mode 100644 index 53ed2e14b7a..00000000000 --- a/examples/aggregate/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "aggregate-example", - "private": "true", - "version": "0.0.0", - "description": "deps for aggregate example", - "main": "aggregate.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/examples/aggregate/person.js b/examples/aggregate/person.js deleted file mode 100644 index 76ec8a0cab4..00000000000 --- a/examples/aggregate/person.js +++ /dev/null @@ -1,19 +0,0 @@ - -// import the necessary modules -'use strict'; - -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - const PersonSchema = new Schema({ - name: String, - age: Number, - birthday: Date, - gender: String, - likes: [String] - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/examples/doc-methods.js b/examples/doc-methods.js deleted file mode 100644 index d6b34599998..00000000000 --- a/examples/doc-methods.js +++ /dev/null @@ -1,78 +0,0 @@ - -'use strict'; -const mongoose = require('mongoose'); -const Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Schema - */ - -const CharacterSchema = Schema({ - name: { - type: String, - required: true - }, - health: { - type: Number, - min: 0, - max: 100 - } -}); - -/** - * Methods - */ - -CharacterSchema.methods.attack = function() { - console.log('%s is attacking', this.name); -}; - -/** - * Character model - */ - -const Character = mongoose.model('Character', CharacterSchema); - -/** - * Connect to the database on 127.0.0.1 with - * the default port (27017) - */ - -const dbname = 'mongoose-example-doc-methods-' + ((Math.random() * 10000) | 0); -const uri = 'mongodb://127.0.0.1/' + dbname; - -console.log('connecting to %s', uri); - -mongoose.connect(uri, function(err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - example(); -}); - -/** - * Use case - */ - -function example() { - Character.create({ name: 'Link', health: 100 }, function(err, link) { - if (err) return done(err); - console.log('found', link); - link.attack(); // 'Link is attacking' - done(); - }); -} - -/** - * Clean up - */ - -function done(err) { - if (err) console.error(err); - mongoose.connection.db.dropDatabase(function() { - mongoose.disconnect(); - }); -} diff --git a/examples/express/README.md b/examples/express/README.md deleted file mode 100644 index c3caa9c088d..00000000000 --- a/examples/express/README.md +++ /dev/null @@ -1 +0,0 @@ -# Mongoose + Express examples diff --git a/examples/express/connection-sharing/README.md b/examples/express/connection-sharing/README.md deleted file mode 100644 index b734d875bd8..00000000000 --- a/examples/express/connection-sharing/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Express Connection sharing Example - -To run: - -* Execute `npm install` from this directory -* Execute `node app.js` -* Navigate to `127.0.0.1:8000` diff --git a/examples/express/connection-sharing/app.js b/examples/express/connection-sharing/app.js deleted file mode 100644 index 8c0efae338e..00000000000 --- a/examples/express/connection-sharing/app.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; -const express = require('express'); -const mongoose = require('../../../lib'); - -const uri = 'mongodb://127.0.0.1/mongoose-shared-connection'; -global.db = mongoose.createConnection(uri); - -const routes = require('./routes'); - -const app = express(); -app.get('/', routes.home); -app.get('/insert', routes.insert); -app.get('/name', routes.modelName); - -app.listen(8000, () => console.log('listening on http://127.0.0.1:8000')); diff --git a/examples/express/connection-sharing/modelA.js b/examples/express/connection-sharing/modelA.js deleted file mode 100644 index b52e20c0420..00000000000 --- a/examples/express/connection-sharing/modelA.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; -const Schema = require('../../../lib').Schema; -const mySchema = Schema({ name: String }); - -/* global db */ -module.exports = db.model('MyModel', mySchema); diff --git a/examples/express/connection-sharing/package.json b/examples/express/connection-sharing/package.json deleted file mode 100644 index f53b7c7b3cb..00000000000 --- a/examples/express/connection-sharing/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "connection-sharing", - "private": true, - "version": "0.0.0", - "description": "ERROR: No README.md file found!", - "main": "app.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "express": "4.x" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/examples/express/connection-sharing/routes.js b/examples/express/connection-sharing/routes.js deleted file mode 100644 index e9d483ae285..00000000000 --- a/examples/express/connection-sharing/routes.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; -const model = require('./modelA'); - -exports.home = async(req, res, next) => { - try { - const docs = await model.find(); - res.send(docs); - } catch (err) { - next(err); - } -}; - -exports.modelName = (req, res) => { - res.send('my model name is ' + model.modelName); -}; - -exports.insert = async(req, res, next) => { - try { - const doc = await model.create({ name: 'inserting ' + Date.now() }); - res.send(doc); - } catch (err) { - next(err); - } -}; diff --git a/examples/geospatial/geoJSONSchema.js b/examples/geospatial/geoJSONSchema.js deleted file mode 100644 index ae3d10675e2..00000000000 --- a/examples/geospatial/geoJSONSchema.js +++ /dev/null @@ -1,24 +0,0 @@ - -// import the necessary modules -'use strict'; - -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - // NOTE : This object must conform *precisely* to the geoJSON specification - // you cannot embed a geoJSON doc inside a model or anything like that- IT - // MUST BE VANILLA - const LocationObject = new Schema({ - loc: { - type: { type: String }, - coordinates: [] - } - }); - // define the index - LocationObject.index({ loc: '2dsphere' }); - - mongoose.model('Location', LocationObject); -}; diff --git a/examples/geospatial/geoJSONexample.js b/examples/geospatial/geoJSONexample.js deleted file mode 100644 index 5f1fd2dbb87..00000000000 --- a/examples/geospatial/geoJSONexample.js +++ /dev/null @@ -1,58 +0,0 @@ -// import async to make control flow simplier -'use strict'; - -const async = require('async'); - -// import the rest of the normal stuff -const mongoose = require('../../lib'); - -require('./geoJSONSchema.js')(); - -const Location = mongoose.model('Location'); - -// define some dummy data -// note: the type can be Point, LineString, or Polygon -const data = [ - { loc: { type: 'Point', coordinates: [-20.0, 5.0] } }, - { loc: { type: 'Point', coordinates: [6.0, 10.0] } }, - { loc: { type: 'Point', coordinates: [34.0, -50.0] } }, - { loc: { type: 'Point', coordinates: [-100.0, 70.0] } }, - { loc: { type: 'Point', coordinates: [38.0, 38.0] } } -]; - - -mongoose.connect('mongodb://127.0.0.1/locations', function(err) { - if (err) { - throw err; - } - - Location.on('index', function(err) { - if (err) { - throw err; - } - // create all of the dummy locations - async.each(data, function(item, cb) { - Location.create(item, cb); - }, function(err) { - if (err) { - throw err; - } - // create the location we want to search for - const coords = { type: 'Point', coordinates: [-5, 5] }; - // search for it - Location.find({ loc: { $near: coords } }).limit(1).exec(function(err, res) { - if (err) { - throw err; - } - console.log('Closest to %s is %s', JSON.stringify(coords), res); - cleanup(); - }); - }); - }); -}); - -function cleanup() { - Location.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/examples/geospatial/geospatial.js b/examples/geospatial/geospatial.js deleted file mode 100644 index 8bebb6b2166..00000000000 --- a/examples/geospatial/geospatial.js +++ /dev/null @@ -1,102 +0,0 @@ -// import async to make control flow simplier -'use strict'; - -const async = require('async'); - -// import the rest of the normal stuff -const mongoose = require('../../lib'); - -require('./person.js')(); - -const Person = mongoose.model('Person'); - -// define some dummy data -const data = [ - { - name: 'bill', - age: 25, - birthday: new Date().setFullYear((new Date().getFullYear() - 25)), - gender: 'Male', - likes: ['movies', 'games', 'dogs'], - loc: [0, 0] - }, - { - name: 'mary', - age: 30, - birthday: new Date().setFullYear((new Date().getFullYear() - 30)), - gender: 'Female', - likes: ['movies', 'birds', 'cats'], - loc: [1, 1] - }, - { - name: 'bob', - age: 21, - birthday: new Date().setFullYear((new Date().getFullYear() - 21)), - gender: 'Male', - likes: ['tv', 'games', 'rabbits'], - loc: [3, 3] - }, - { - name: 'lilly', - age: 26, - birthday: new Date().setFullYear((new Date().getFullYear() - 26)), - gender: 'Female', - likes: ['books', 'cats', 'dogs'], - loc: [6, 6] - }, - { - name: 'alucard', - age: 1000, - birthday: new Date().setFullYear((new Date().getFullYear() - 1000)), - gender: 'Male', - likes: ['glasses', 'wine', 'the night'], - loc: [10, 10] - } -]; - - -mongoose.connect('mongodb://127.0.0.1/persons', function(err) { - if (err) { - throw err; - } - - // create all of the dummy people - async.each(data, function(item, cb) { - Person.create(item, cb); - }, function(err) { - if (err) { - // handler error - } - - // let's find the closest person to bob - Person.find({ name: 'bob' }, function(err, res) { - if (err) { - throw err; - } - - res[0].findClosest(function(err, closest) { - if (err) { - throw err; - } - - console.log('%s is closest to %s', res[0].name, closest); - - - // we can also just query straight off of the model. For more - // information about geospatial queries and indexes, see - // http://www.mongodb.com/docs/manual/applications/geospatial-indexes/ - const coords = [7, 7]; - Person.find({ loc: { $nearSphere: coords } }).limit(1).exec(function(err, res) { - console.log('Closest to %s is %s', coords, res); - cleanup(); - }); - }); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/examples/geospatial/package.json b/examples/geospatial/package.json deleted file mode 100644 index 75c2a0eef22..00000000000 --- a/examples/geospatial/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "geospatial-example", - "private": "true", - "version": "0.0.0", - "description": "deps for geospatial example", - "main": "geospatial.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/examples/geospatial/person.js b/examples/geospatial/person.js deleted file mode 100644 index 9f692320bb5..00000000000 --- a/examples/geospatial/person.js +++ /dev/null @@ -1,29 +0,0 @@ -// import the necessary modules -'use strict'; - -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - const PersonSchema = new Schema({ - name: String, - age: Number, - birthday: Date, - gender: String, - likes: [String], - // define the geospatial field - loc: { type: [Number], index: '2d' } - }); - - // define a method to find the closest person - PersonSchema.methods.findClosest = function(cb) { - return mongoose.model('Person').find({ - loc: { $nearSphere: this.loc }, - name: { $ne: this.name } - }).limit(1).exec(cb); - }; - - mongoose.model('Person', PersonSchema); -}; diff --git a/examples/globalschemas/gs_example.js b/examples/globalschemas/gs_example.js deleted file mode 100644 index 3b9a74f9dd5..00000000000 --- a/examples/globalschemas/gs_example.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; -const mongoose = require('../../lib'); - - -// import the global schema, this can be done in any file that needs the model -require('./person.js')(); - -// grab the person model object -const Person = mongoose.model('Person'); - -// connect to a server to do a quick write / read example - -mongoose.connect('mongodb://127.0.0.1/persons', function(err) { - if (err) { - throw err; - } - - Person.create({ - name: 'bill', - age: 25, - birthday: new Date().setFullYear((new Date().getFullYear() - 25)) - }, function(err, bill) { - if (err) { - throw err; - } - console.log('People added to db: %s', bill.toString()); - Person.find({}, function(err, people) { - if (err) { - throw err; - } - - people.forEach(function(person) { - console.log('People in the db: %s', person.toString()); - }); - - // make sure to clean things up after we're done - setTimeout(function() { - cleanup(); - }, 2000); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/examples/globalschemas/person.js b/examples/globalschemas/person.js deleted file mode 100644 index f598dd3fb63..00000000000 --- a/examples/globalschemas/person.js +++ /dev/null @@ -1,16 +0,0 @@ -// import the necessary modules -'use strict'; - -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - const PersonSchema = new Schema({ - name: String, - age: Number, - birthday: Date - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/examples/lean/lean.js b/examples/lean/lean.js deleted file mode 100644 index 95759a40a6b..00000000000 --- a/examples/lean/lean.js +++ /dev/null @@ -1,86 +0,0 @@ - -// import async to make control flow simplier -'use strict'; - -const async = require('async'); - -// import the rest of the normal stuff -const mongoose = require('../../lib'); - -require('./person.js')(); - -const Person = mongoose.model('Person'); - -// define some dummy data -const data = [ - { - name: 'bill', - age: 25, - birthday: new Date().setFullYear((new Date().getFullYear() - 25)), - gender: 'Male', - likes: ['movies', 'games', 'dogs'] - }, - { - name: 'mary', - age: 30, - birthday: new Date().setFullYear((new Date().getFullYear() - 30)), - gender: 'Female', - likes: ['movies', 'birds', 'cats'] - }, - { - name: 'bob', - age: 21, - birthday: new Date().setFullYear((new Date().getFullYear() - 21)), - gender: 'Male', - likes: ['tv', 'games', 'rabbits'] - }, - { - name: 'lilly', - age: 26, - birthday: new Date().setFullYear((new Date().getFullYear() - 26)), - gender: 'Female', - likes: ['books', 'cats', 'dogs'] - }, - { - name: 'alucard', - age: 1000, - birthday: new Date().setFullYear((new Date().getFullYear() - 1000)), - gender: 'Male', - likes: ['glasses', 'wine', 'the night'] - } -]; - - -mongoose.connect('mongodb://127.0.0.1/persons', function(err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function(item, cb) { - Person.create(item, cb); - }, function(err) { - if (err) { - // handle error - } - - // lean queries return just plain javascript objects, not - // MongooseDocuments. This makes them good for high performance read - // situations - - // when using .lean() the default is true, but you can explicitly set the - // value by passing in a boolean value. IE. .lean(false) - const q = Person.find({ age: { $lt: 1000 } }).sort('age').limit(2).lean(); - q.exec(function(err, results) { - if (err) throw err; - console.log('Are the results MongooseDocuments?: %s', results[0] instanceof mongoose.Document); - - console.log(results); - cleanup(); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/examples/lean/package.json b/examples/lean/package.json deleted file mode 100644 index 6ee511de77a..00000000000 --- a/examples/lean/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "lean-example", - "private": "true", - "version": "0.0.0", - "description": "deps for lean example", - "main": "lean.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/examples/lean/person.js b/examples/lean/person.js deleted file mode 100644 index c052f7f24df..00000000000 --- a/examples/lean/person.js +++ /dev/null @@ -1,18 +0,0 @@ -// import the necessary modules -'use strict'; - -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - const PersonSchema = new Schema({ - name: String, - age: Number, - birthday: Date, - gender: String, - likes: [String] - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/examples/population/population-across-three-collections.js b/examples/population/population-across-three-collections.js deleted file mode 100644 index e3ef031d9b9..00000000000 --- a/examples/population/population-across-three-collections.js +++ /dev/null @@ -1,135 +0,0 @@ - -'use strict'; -const assert = require('assert'); -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; -const ObjectId = mongoose.Types.ObjectId; - -/** - * Connect to the db - */ - -const dbname = 'testing_populateAdInfinitum_' + require('../../lib/utils').random(); -mongoose.connect('127.0.0.1', dbname); -mongoose.connection.on('error', function() { - console.error('connection error', arguments); -}); - -/** - * Schemas - */ - -const user = new Schema({ - name: String, - friends: [{ - type: Schema.ObjectId, - ref: 'User' - }] -}); -const User = mongoose.model('User', user); - -const blogpost = Schema({ - title: String, - tags: [String], - author: { - type: Schema.ObjectId, - ref: 'User' - } -}); -const BlogPost = mongoose.model('BlogPost', blogpost); - -/** - * example - */ - -mongoose.connection.on('open', function() { - /** - * Generate data - */ - - const userIds = [new ObjectId(), new ObjectId(), new ObjectId(), new ObjectId()]; - const users = []; - - users.push({ - _id: userIds[0], - name: 'mary', - friends: [userIds[1], userIds[2], userIds[3]] - }); - users.push({ - _id: userIds[1], - name: 'bob', - friends: [userIds[0], userIds[2], userIds[3]] - }); - users.push({ - _id: userIds[2], - name: 'joe', - friends: [userIds[0], userIds[1], userIds[3]] - }); - users.push({ - _id: userIds[3], - name: 'sally', - friends: [userIds[0], userIds[1], userIds[2]] - }); - - User.create(users, function(err) { - assert.ifError(err); - - const blogposts = []; - blogposts.push({ - title: 'blog 1', - tags: ['fun', 'cool'], - author: userIds[3] - }); - blogposts.push({ - title: 'blog 2', - tags: ['cool'], - author: userIds[1] - }); - blogposts.push({ - title: 'blog 3', - tags: ['fun', 'odd'], - author: userIds[2] - }); - - BlogPost.create(blogposts, function(err) { - assert.ifError(err); - - /** - * Population - */ - - BlogPost - .find({ tags: 'fun' }) - .lean() - .populate('author') - .exec(function(err, docs) { - assert.ifError(err); - - /** - * Populate the populated documents - */ - - const opts = { - path: 'author.friends', - select: 'name', - options: { limit: 2 } - }; - - BlogPost.populate(docs, opts, function(err, docs) { - assert.ifError(err); - console.log('populated'); - const s = require('util').inspect(docs, { depth: null, colors: true }); - console.log(s); - done(); - }); - }); - }); - }); -}); - -function done(err) { - if (err) console.error(err.stack); - mongoose.connection.db.dropDatabase(function() { - mongoose.connection.close(); - }); -} diff --git a/examples/population/population-basic.js b/examples/population/population-basic.js deleted file mode 100644 index a6c7ea88c7f..00000000000 --- a/examples/population/population-basic.js +++ /dev/null @@ -1,104 +0,0 @@ - -'use strict'; -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -const consoleSchema = Schema({ - name: String, - manufacturer: String, - released: Date -}); -const Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -const gameSchema = Schema({ - name: String, - developer: String, - released: Date, - consoles: [{ - type: Schema.Types.ObjectId, - ref: 'Console' - }] -}); -const Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on 127.0.0.1 with - * the default port (27017) - */ - -mongoose.connect('mongodb://127.0.0.1/console', function(err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}); - -/** - * Data generation - */ - -function createData() { - Console.create( - { - name: 'Nintendo 64', - manufacturer: 'Nintendo', - released: 'September 29, 1996' - }, - function(err, nintendo64) { - if (err) return done(err); - - Game.create({ - name: 'Legend of Zelda: Ocarina of Time', - developer: 'Nintendo', - released: new Date('November 21, 1998'), - consoles: [nintendo64] - }, - function(err) { - if (err) return done(err); - example(); - }); - } - ); -} - -/** - * Population - */ - -function example() { - Game - .findOne({ name: /^Legend of Zelda/ }) - .populate('consoles') - .exec(function(err, ocinara) { - if (err) return done(err); - - console.log( - '"%s" was released for the %s on %s', - ocinara.name, - ocinara.consoles[0].name, - ocinara.released.toLocaleDateString() - ); - - done(); - }); -} - -function done(err) { - if (err) console.error(err); - Console.remove(function() { - Game.remove(function() { - mongoose.disconnect(); - }); - }); -} diff --git a/examples/population/population-of-existing-doc.js b/examples/population/population-of-existing-doc.js deleted file mode 100644 index 4223f3ae9e4..00000000000 --- a/examples/population/population-of-existing-doc.js +++ /dev/null @@ -1,110 +0,0 @@ - -'use strict'; -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -const consoleSchema = Schema({ - name: String, - manufacturer: String, - released: Date -}); -const Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -const gameSchema = Schema({ - name: String, - developer: String, - released: Date, - consoles: [{ - type: Schema.Types.ObjectId, - ref: 'Console' - }] -}); -const Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on 127.0.0.1 with - * the default port (27017) - */ - -mongoose.connect('mongodb://127.0.0.1/console', function(err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}); - -/** - * Data generation - */ - -function createData() { - Console.create( - { - name: 'Nintendo 64', - manufacturer: 'Nintendo', - released: 'September 29, 1996' - }, - function(err, nintendo64) { - if (err) return done(err); - - Game.create({ - name: 'Legend of Zelda: Ocarina of Time', - developer: 'Nintendo', - released: new Date('November 21, 1998'), - consoles: [nintendo64] - }, - function(err) { - if (err) return done(err); - example(); - }); - } - ); -} - -/** - * Population - */ - -function example() { - Game - .findOne({ name: /^Legend of Zelda/ }) - .exec(function(err, ocinara) { - if (err) return done(err); - - console.log('"%s" console _id: %s', ocinara.name, ocinara.consoles[0]); - - // population of existing document - ocinara.populate('consoles', function(err) { - if (err) return done(err); - - console.log( - '"%s" was released for the %s on %s', - ocinara.name, - ocinara.consoles[0].name, - ocinara.released.toLocaleDateString() - ); - - done(); - }); - }); -} - -function done(err) { - if (err) console.error(err); - Console.remove(function() { - Game.remove(function() { - mongoose.disconnect(); - }); - }); -} diff --git a/examples/population/population-of-multiple-existing-docs.js b/examples/population/population-of-multiple-existing-docs.js deleted file mode 100644 index 310d0a40c05..00000000000 --- a/examples/population/population-of-multiple-existing-docs.js +++ /dev/null @@ -1,125 +0,0 @@ - -'use strict'; -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -const consoleSchema = Schema({ - name: String, - manufacturer: String, - released: Date -}); -const Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -const gameSchema = Schema({ - name: String, - developer: String, - released: Date, - consoles: [{ - type: Schema.Types.ObjectId, - ref: 'Console' - }] -}); -const Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on 127.0.0.1 with - * the default port (27017) - */ - -mongoose.connect('mongodb://127.0.0.1/console', function(err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}); - -/** - * Data generation - */ - -function createData() { - Console.create( - { - name: 'Nintendo 64', - manufacturer: 'Nintendo', - released: 'September 29, 1996' - }, - { - name: 'Super Nintendo', - manufacturer: 'Nintendo', - released: 'August 23, 1991' - }, - function(err, nintendo64, superNintendo) { - if (err) return done(err); - - Game.create( - { - name: 'Legend of Zelda: Ocarina of Time', - developer: 'Nintendo', - released: new Date('November 21, 1998'), - consoles: [nintendo64] - }, - { - name: 'Mario Kart', - developer: 'Nintendo', - released: 'September 1, 1992', - consoles: [superNintendo] - }, - function(err) { - if (err) return done(err); - example(); - } - ); - } - ); -} - -/** - * Population - */ - -function example() { - Game - .find({}) - .exec(function(err, games) { - if (err) return done(err); - - console.log('found %d games', games.length); - - const options = { path: 'consoles', select: 'name released -_id' }; - Game.populate(games, options, function(err, games) { - if (err) return done(err); - - games.forEach(function(game) { - console.log( - '"%s" was released for the %s on %s', - game.name, - game.consoles[0].name, - game.released.toLocaleDateString() - ); - }); - - done(); - }); - }); -} - -function done(err) { - if (err) console.error(err); - Console.remove(function() { - Game.remove(function() { - mongoose.disconnect(); - }); - }); -} diff --git a/examples/population/population-options.js b/examples/population/population-options.js deleted file mode 100644 index 2e75556ddd4..00000000000 --- a/examples/population/population-options.js +++ /dev/null @@ -1,139 +0,0 @@ - -'use strict'; -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -const consoleSchema = Schema({ - name: String, - manufacturer: String, - released: Date -}); -const Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -const gameSchema = Schema({ - name: String, - developer: String, - released: Date, - consoles: [{ - type: Schema.Types.ObjectId, - ref: 'Console' - }] -}); -const Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on 127.0.0.1 with - * the default port (27017) - */ - -mongoose.connect('mongodb://127.0.0.1/console', function(err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}); - -/** - * Data generation - */ - -function createData() { - Console.create( - { - name: 'Nintendo 64', - manufacturer: 'Nintendo', - released: 'September 29, 1996' - }, - { - name: 'Super Nintendo', - manufacturer: 'Nintendo', - released: 'August 23, 1991' - }, - { - name: 'XBOX 360', - manufacturer: 'Microsoft', - released: 'November 22, 2005' - }, - function(err, nintendo64, superNintendo, xbox360) { - if (err) return done(err); - - Game.create( - { - name: 'Legend of Zelda: Ocarina of Time', - developer: 'Nintendo', - released: new Date('November 21, 1998'), - consoles: [nintendo64] - }, - { - name: 'Mario Kart', - developer: 'Nintendo', - released: 'September 1, 1992', - consoles: [superNintendo] - }, - { - name: 'Perfect Dark Zero', - developer: 'Rare', - released: 'November 17, 2005', - consoles: [xbox360] - }, - function(err) { - if (err) return done(err); - example(); - } - ); - } - ); -} - -/** - * Population - */ - -function example() { - Game - .find({}) - .populate({ - path: 'consoles', - match: { manufacturer: 'Nintendo' }, - select: 'name', - options: { comment: 'population' } - }) - .exec(function(err, games) { - if (err) return done(err); - - games.forEach(function(game) { - console.log( - '"%s" was released for the %s on %s', - game.name, - game.consoles.length ? game.consoles[0].name : '??', - game.released.toLocaleDateString() - ); - }); - - return done(); - }); -} - -/** - * Clean up - */ - -function done(err) { - if (err) console.error(err); - Console.remove(function() { - Game.remove(function() { - mongoose.disconnect(); - }); - }); -} diff --git a/examples/population/population-plain-objects.js b/examples/population/population-plain-objects.js deleted file mode 100644 index ed5abe03d1e..00000000000 --- a/examples/population/population-plain-objects.js +++ /dev/null @@ -1,107 +0,0 @@ - -'use strict'; -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -const consoleSchema = Schema({ - name: String, - manufacturer: String, - released: Date -}); -const Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -const gameSchema = Schema({ - name: String, - developer: String, - released: Date, - consoles: [{ - type: Schema.Types.ObjectId, - ref: 'Console' - }] -}); -const Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on 127.0.0.1 with - * the default port (27017) - */ - -mongoose.connect('mongodb://127.0.0.1/console', function(err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}); - -/** - * Data generation - */ - -function createData() { - Console.create( - { - name: 'Nintendo 64', - manufacturer: 'Nintendo', - released: 'September 29, 1996' - }, - function(err, nintendo64) { - if (err) return done(err); - - Game.create( - { - name: 'Legend of Zelda: Ocarina of Time', - developer: 'Nintendo', - released: new Date('November 21, 1998'), - consoles: [nintendo64] - }, - function(err) { - if (err) return done(err); - example(); - } - ); - } - ); -} - -/** - * Population - */ - -function example() { - Game - .findOne({ name: /^Legend of Zelda/ }) - .populate('consoles') - .lean() // just return plain objects, not documents wrapped by mongoose - .exec(function(err, ocinara) { - if (err) return done(err); - - console.log( - '"%s" was released for the %s on %s', - ocinara.name, - ocinara.consoles[0].name, - ocinara.released.toLocaleDateString() - ); - - done(); - }); -} - -function done(err) { - if (err) console.error(err); - Console.remove(function() { - Game.remove(function() { - mongoose.disconnect(); - }); - }); -} diff --git a/examples/promises/package.json b/examples/promises/package.json deleted file mode 100644 index 19832508002..00000000000 --- a/examples/promises/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "promise-example", - "private": "true", - "version": "0.0.0", - "description": "deps for promise example", - "main": "promise.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/examples/promises/person.js b/examples/promises/person.js deleted file mode 100644 index 2f8f6b04299..00000000000 --- a/examples/promises/person.js +++ /dev/null @@ -1,17 +0,0 @@ - -// import the necessary modules -'use strict'; - -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - const PersonSchema = new Schema({ - name: String, - age: Number, - birthday: Date - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/examples/promises/promise.js b/examples/promises/promise.js deleted file mode 100644 index a0660c9a1a0..00000000000 --- a/examples/promises/promise.js +++ /dev/null @@ -1,96 +0,0 @@ -// import async to make control flow simplier -'use strict'; - -const async = require('async'); - -// import the rest of the normal stuff -const mongoose = require('../../lib'); - -require('./person.js')(); - -const Person = mongoose.model('Person'); - -// define some dummy data -const data = [ - { - name: 'bill', - age: 25, - birthday: new Date().setFullYear((new Date().getFullYear() - 25)) - }, - { - name: 'mary', - age: 30, - birthday: new Date().setFullYear((new Date().getFullYear() - 30)) - }, - { - name: 'bob', - age: 21, - birthday: new Date().setFullYear((new Date().getFullYear() - 21)) - }, - { - name: 'lilly', - age: 26, - birthday: new Date().setFullYear((new Date().getFullYear() - 26)) - }, - { - name: 'alucard', - age: 1000, - birthday: new Date().setFullYear((new Date().getFullYear() - 1000)) - } -]; - - -mongoose.connect('mongodb://127.0.0.1/persons', function(err) { - if (err) { - throw err; - } - - // create all of the dummy people - async.each(data, function(item, cb) { - Person.create(item, cb); - }, function(err) { - if (err) { - // handle error - } - - // create a promise (get one from the query builder) - const prom = Person.find({ age: { $lt: 1000 } }).exec(); - - // add a callback on the promise. This will be called on both error and - // complete - prom.addBack(function() { - console.log('completed'); - }); - - // add a callback that is only called on complete (success) events - prom.addCallback(function() { - console.log('Successful Completion!'); - }); - - // add a callback that is only called on err (rejected) events - prom.addErrback(function() { - console.log('Fail Boat'); - }); - - // you can chain things just like in the promise/A+ spec - // note: each then() is returning a new promise, so the above methods - // that we defined will all fire after the initial promise is fulfilled - prom.then(function(people) { - // just getting the stuff for the next query - const ids = people.map(function(p) { - return p._id; - }); - - // return the next promise - return Person.find({ _id: { $nin: ids } }).exec(); - }).then(function(oldest) { - console.log('Oldest person is: %s', oldest); - }).then(cleanup); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/examples/querybuilder/package.json b/examples/querybuilder/package.json deleted file mode 100644 index 1a3450aa159..00000000000 --- a/examples/querybuilder/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "query-builder-example", - "private": "true", - "version": "0.0.0", - "description": "deps for query builder example", - "main": "querybuilder.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/examples/querybuilder/person.js b/examples/querybuilder/person.js deleted file mode 100644 index 2f8f6b04299..00000000000 --- a/examples/querybuilder/person.js +++ /dev/null @@ -1,17 +0,0 @@ - -// import the necessary modules -'use strict'; - -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - const PersonSchema = new Schema({ - name: String, - age: Number, - birthday: Date - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/examples/querybuilder/querybuilder.js b/examples/querybuilder/querybuilder.js deleted file mode 100644 index a05059c001c..00000000000 --- a/examples/querybuilder/querybuilder.js +++ /dev/null @@ -1,81 +0,0 @@ - -// import async to make control flow simplier -'use strict'; - -const async = require('async'); - -// import the rest of the normal stuff -const mongoose = require('../../lib'); - -require('./person.js')(); - -const Person = mongoose.model('Person'); - -// define some dummy data -const data = [ - { - name: 'bill', - age: 25, - birthday: new Date().setFullYear((new Date().getFullYear() - 25)) - }, - { - name: 'mary', - age: 30, - birthday: new Date().setFullYear((new Date().getFullYear() - 30)) - }, - { - name: 'bob', - age: 21, - birthday: new Date().setFullYear((new Date().getFullYear() - 21)) - }, - { - name: 'lilly', - age: 26, - birthday: new Date().setFullYear((new Date().getFullYear() - 26)) - }, - { - name: 'alucard', - age: 1000, - birthday: new Date().setFullYear((new Date().getFullYear() - 1000)) - } -]; - - -mongoose.connect('mongodb://127.0.0.1/persons', function(err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function(item, cb) { - Person.create(item, cb); - }, function(err) { - if (err) throw err; - - // when querying data, instead of providing a callback, you can instead - // leave that off and get a query object returned - const query = Person.find({ age: { $lt: 1000 } }); - - // this allows you to continue applying modifiers to it - query.sort('birthday'); - query.select('name'); - - // you can chain them together as well - // a full list of methods can be found: - // http://mongoosejs.com/docs/api/query.html - query.where('age').gt(21); - - // finally, when ready to execute the query, call the exec() function - query.exec(function(err, results) { - if (err) throw err; - - console.log(results); - - cleanup(); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/examples/redis-todo/.eslintrc.yml b/examples/redis-todo/.eslintrc.yml deleted file mode 100644 index a41589b37c8..00000000000 --- a/examples/redis-todo/.eslintrc.yml +++ /dev/null @@ -1,2 +0,0 @@ -parserOptions: - ecmaVersion: 2019 \ No newline at end of file diff --git a/examples/redis-todo/.npmrc b/examples/redis-todo/.npmrc deleted file mode 100644 index 9cf9495031e..00000000000 --- a/examples/redis-todo/.npmrc +++ /dev/null @@ -1 +0,0 @@ -package-lock=false \ No newline at end of file diff --git a/examples/redis-todo/config.js b/examples/redis-todo/config.js deleted file mode 100644 index 5d5c1179a01..00000000000 --- a/examples/redis-todo/config.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -const JWT_SECRET = 'token'; - -module.exports = { - JWT_SECRET -}; diff --git a/examples/redis-todo/db/index.js b/examples/redis-todo/db/index.js deleted file mode 100644 index c12d30bd323..00000000000 --- a/examples/redis-todo/db/index.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -const mongoose = require('mongoose'); - -mongoose.connect('mongodb://127.0.0.1/redis-todo'); diff --git a/examples/redis-todo/db/models/todoModel.js b/examples/redis-todo/db/models/todoModel.js deleted file mode 100644 index 42ebe6c1a94..00000000000 --- a/examples/redis-todo/db/models/todoModel.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -const mongoose = require('mongoose'); - -const todoSchema = new mongoose.Schema({ - text: { type: String, required: true }, - completed: { type: Boolean, default: false }, - userId: { type: mongoose.Types.ObjectId, required: true } -}, { timestamps: true, versionKey: false }); - -module.exports = mongoose.model('Todo', todoSchema); diff --git a/examples/redis-todo/db/models/userModel.js b/examples/redis-todo/db/models/userModel.js deleted file mode 100644 index b2d2919516a..00000000000 --- a/examples/redis-todo/db/models/userModel.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict'; - -const mongoose = require('mongoose'); -const jwt = require('jsonwebtoken'); -const bcrypt = require('bcryptjs'); -const JWT_SECRET = require('../../config').JWT_SECRET; - -const { Schema, model } = mongoose; - -const userSchema = new Schema({ - name: { type: String, required: true }, - username: { type: String, unique: true, required: true }, - email: { type: String, unique: true, required: true }, - passwordId: { type: mongoose.Types.ObjectId, ref: 'Password' } -}, { timestamps: true, versionKey: false }); - -const userPasswordSchema = new Schema({ - password: { type: String, required: true } -}); - -userSchema.methods.toJSON = function() { - const user = this.toObject(); // this = user - delete user.password; - delete user.email; - return user; -}; - -// creating token -userSchema.methods.genAuthToken = function() { - return jwt.sign({ userId: this._id.toString() }, JWT_SECRET); // this = user -}; - -// password hasing -userPasswordSchema.pre('save', async function(next) { - try { - if (this.isModified('password')) { - this.password = await bcrypt.hashSync(this.password, 8); - return next(); - } - next(); - } catch (err) { - return next(err); - } -}); - -module.exports = { - User: model('User', userSchema), - Password: model('Password', userPasswordSchema) -}; diff --git a/examples/redis-todo/middleware/auth.js b/examples/redis-todo/middleware/auth.js deleted file mode 100644 index 095f2620c99..00000000000 --- a/examples/redis-todo/middleware/auth.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const jwt = require('jsonwebtoken'); -const JWT_SECRET = require('../config').JWT_SECRET; - -module.exports = async function(req, res, next) { - try { - const authToken = req.header('x-auth'); - if (!authToken) return res.status(404).send({ msg: 'AuthToken not found' }); - - const decodedValue = jwt.verify(authToken, JWT_SECRET); - if (!decodedValue) return res.status(401).send({ msg: 'Invalid Authentication' }); - - req.userId = decodedValue.userId; - next(); - } catch { - res.status(401).send({ msg: 'Invalid Authentication' }); - } -}; diff --git a/examples/redis-todo/middleware/clearCache.js b/examples/redis-todo/middleware/clearCache.js deleted file mode 100644 index 446d7d4e303..00000000000 --- a/examples/redis-todo/middleware/clearCache.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -const { clearCache } = require('../services/cache'); - -module.exports = async function(req, res, next) { - await next(); // call endpoint - console.log(req.userId); - clearCache(req.userId); -}; diff --git a/examples/redis-todo/package.json b/examples/redis-todo/package.json deleted file mode 100644 index d0606f8242f..00000000000 --- a/examples/redis-todo/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "redis-todo", - "version": "1.0.0", - "description": "todo app build with express redis mongoose", - "main": "server.js", - "scripts": { - "start": "node server.js", - "dev:start": "nodemon server.js", - "fix": "standard --fix || snazzy" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/usama-asfar/redis-todo.git" - }, - "keywords": [ - "express", - "redis", - "mongoose" - ], - "author": "@usama__asfar", - "license": "MIT", - "bugs": { - "url": "https://github.com/usama-asfar/redis-todo/issues" - }, - "homepage": "https://github.com/usama-asfar/redis-todo#readme", - "dependencies": { - "bcryptjs": "^2.4.3", - "express": "^4.18.1", - "express-rate-limit": "^6.4.0", - "jsonwebtoken": "^8.5.1", - "mongoose": "^6.3.5", - "redis": "^4.1.0" - }, - "devDependencies": { - "nodemon": "^2.0.16", - "morgan": "^1.9.1", - "snazzy": "^9.0.0", - "standard": "^17.0.0" - } -} diff --git a/examples/redis-todo/routers/todoRouter.js b/examples/redis-todo/routers/todoRouter.js deleted file mode 100644 index b88174f72b6..00000000000 --- a/examples/redis-todo/routers/todoRouter.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -const Router = require('express').Router(); -const Todo = require('../db/models/todoModel'); -const auth = require('../middleware/auth'); -const clearCache = require('../middleware/clearCache'); - -/* @api private - * @func: fetch all user todos - * @input: user id - * @return: todos - */ -Router.get('/all', auth, async function({ userId }, res) { - try { - res.status(200).json({ todos: await Todo.find({ userId }).sort({ createdAt: -1 }).cache({ key: userId }) }); - } catch (err) { - console.log(err); - res.status(501).send('Server Error'); - } -}); - -/* @api private - * @func: create todo - * @input: todo data, userid - * @return: todo - */ -Router.post('/create', auth, clearCache, async function({ userId, body }, res) { - try { - const todo = new Todo({ - text: body.text, - completed: body.completed, - userId - }); - await todo.save(); - res.status(201).json({ todo }); - } catch { - res.status(501).send('Server Error'); - } -}); - -/* @api private - * @func: update todo - * @input: todo data, todoId, userid - * @return: updated todo - */ -Router.post('/update', auth, async function({ userId, body }, res) { - try { - const updatedTodo = await Todo.findOneAndUpdate({ $and: [{ userId }, { _id: body.todoId }] }, - { ...body }, { new: true, sanitizeFilter: true } - ); - if (!updatedTodo) return res.status(404).send({ msg: 'Todo not found' }); - - await updatedTodo.save(); - res.status(200).json({ todo: updatedTodo }); - } catch { - res.status(501).send('Server Error'); - } -}); - -/* @api private - * @func: delete todo - * @input: todoId, userid - */ -Router.delete('/delete', auth, async function({ userId, body: { todoId } }, res) { - try { - await Todo.findOneAndDelete({ $and: [{ userId }, { _id: todoId }] }); - res.status(200).send({ msg: 'Todo deleted' }); - } catch { - res.status(501).send('Server Error'); - } -}); - -module.exports = Router; diff --git a/examples/redis-todo/routers/userRouter.js b/examples/redis-todo/routers/userRouter.js deleted file mode 100644 index 763808df46d..00000000000 --- a/examples/redis-todo/routers/userRouter.js +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; - -const Router = require('express').Router(); -const bcrypt = require('bcryptjs'); -const { User, Password } = require('../db/models/userModel'); -const Todo = require('../db/models/todoModel'); -const auth = require('../middleware/auth'); - -/* @public - * @func: create new user - * @input: username,name,email and password - * @return: auth token - */ -Router.post('/create', async function({ body }, res) { - try { - // storing password - const password = new Password({ password: body.password }); - const user = new User({ - name: body.name, - username: body.username, - email: body.email, - passwordId: password._id - }); // body = user data - - // gen auth token - const token = await user.genAuthToken(); - - // hashing password - await password.save(); - await user.save(); - res.status(201).json({ token }); - } catch (err) { - console.log(err); - res.status(501).send('Server Error'); - } -}); - -/* @public - * @func: login user - * @input: user/email, password - * @return: auth token - */ -Router.post('/login', async function({ body }, res) { - try { - const user = await User.findOne( - { $or: [{ email: body.email }, { username: body.username }] } - ).populate('passwordId'); - if (!user) return res.status(404).send({ msg: 'Invalid credential' }); - - const isPassword = await bcrypt.compare(body.password, user.passwordId.password); - if (!isPassword) return res.status(404).send({ msg: 'Invalid credential' }); - - const token = user.genAuthToken(); - res.status(201).json({ token }); - } catch { - res.status(501).send('Server Error'); - } -}); - -/* @api private - * @func: edit user - * @input: username, name or password - * @return: edited user - */ -Router.post('/update', auth, async function({ userId, body }, res) { - try { - const updatedUser = await User.findByIdAndUpdate( - { _id: userId }, - { ...body }, - { new: true }); - - // if password then hash it - if (body.password) { - const password = await Password.findById({ _id: updatedUser.passwordId }); - password.password = body.password; - password.save(); // hashing password - } - - res.status(200).json({ user: updatedUser }); - } catch { - res.status(500).send('Server Error'); - } -}); - -/* @api private - * @func: delete user - */ -Router.delete('/delete', auth, async function({ userId }, res) { - try { - await User.findByIdAndRemove({ _id: userId }); - await Todo.deleteMany({ userId }); - res.status(200).send({ msg: 'User deleted' }); - } catch { - res.status(501).send('Server Error'); - } -}); - -module.exports = Router; diff --git a/examples/redis-todo/server.js b/examples/redis-todo/server.js deleted file mode 100644 index 8c8b47fe537..00000000000 --- a/examples/redis-todo/server.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -const http = require('http'); -const express = require('express'); -const rateLimit = require('express-rate-limit'); - -// DB -require('./db'); -require('./services/cache'); - -const limiter = rateLimit({ - windowMs: 1 * 60 * 1000, // 1 minute - max: 100 -}); - -const app = express(); -app.use(express.json()); - -app.use(limiter); - -// morgan test -app.use(require('morgan')('dev')); - -// ROUTERS -app.use('/user', require('./routers/userRouter')); -app.use('/todo', require('./routers/todoRouter')); - -// Server setup -const httpServer = http.createServer(app); -const PORT = process.env.PORT || 5000; -httpServer.listen(PORT, () => { - console.log(`Server up at PORT:${PORT}`); -}); diff --git a/examples/redis-todo/services/cache.js b/examples/redis-todo/services/cache.js deleted file mode 100644 index 6b2f1adfa81..00000000000 --- a/examples/redis-todo/services/cache.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -const mongoose = require('mongoose'); -const redis = require('redis'); - -// setting up redis server -const client = redis.createClient(); -client.connect().then(); -const exec = mongoose.Query.prototype.exec; - -mongoose.Query.prototype.cache = function(options = {}) { - this.useCache = true; - // setting up primary user key - this.hashKey = JSON.stringify(options.key || ''); - return this; -}; - -mongoose.Query.prototype.exec = async function() { - if (!this.useCache) return exec.apply(this, arguments); - - // setting up query key - const key = JSON.stringify(Object.assign({}, - this.getQuery(), { collection: this.mongooseCollection.name }) - ); - - // looking for cache - const cacheData = await client.hGet(this.hashKey, key).catch((err) => console.log(err)); - if (cacheData) { - console.log('from redis'); - const doc = JSON.parse(cacheData); - // inserting doc to make as actual mongodb query - return Array.isArray(doc) ? doc.map(d => new this.model(d)) : new this.model(doc); - } - - const result = await exec.apply(this, arguments); - client.hSet(this.hashKey, key, JSON.stringify(result)); - return result; -}; - -module.exports = { - clearCache(hashKey) { - client.del(JSON.stringify(hashKey)); - } -}; diff --git a/examples/replicasets/package.json b/examples/replicasets/package.json deleted file mode 100644 index 927dfd24b83..00000000000 --- a/examples/replicasets/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "replica-set-example", - "private": "true", - "version": "0.0.0", - "description": "deps for replica set example", - "main": "querybuilder.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/examples/replicasets/person.js b/examples/replicasets/person.js deleted file mode 100644 index 2f8f6b04299..00000000000 --- a/examples/replicasets/person.js +++ /dev/null @@ -1,17 +0,0 @@ - -// import the necessary modules -'use strict'; - -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - const PersonSchema = new Schema({ - name: String, - age: Number, - birthday: Date - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/examples/replicasets/replica-sets.js b/examples/replicasets/replica-sets.js deleted file mode 100644 index cb9b91df7e8..00000000000 --- a/examples/replicasets/replica-sets.js +++ /dev/null @@ -1,73 +0,0 @@ - -// import async to make control flow simplier -'use strict'; - -const async = require('async'); - -// import the rest of the normal stuff -const mongoose = require('../../lib'); - -require('./person.js')(); - -const Person = mongoose.model('Person'); - -// define some dummy data -const data = [ - { - name: 'bill', - age: 25, - birthday: new Date().setFullYear((new Date().getFullYear() - 25)) - }, - { - name: 'mary', - age: 30, - birthday: new Date().setFullYear((new Date().getFullYear() - 30)) - }, - { - name: 'bob', - age: 21, - birthday: new Date().setFullYear((new Date().getFullYear() - 21)) - }, - { - name: 'lilly', - age: 26, - birthday: new Date().setFullYear((new Date().getFullYear() - 26)) - }, - { - name: 'alucard', - age: 1000, - birthday: new Date().setFullYear((new Date().getFullYear() - 1000)) - } -]; - - -// to connect to a replica set, pass in the comma delimited uri and optionally -// any connection options such as the rs_name. -const opts = { - replSet: { rs_name: 'rs0' } -}; -mongoose.connect('mongodb://127.0.0.1:27018/persons,127.0.0.1:27019,127.0.0.1:27020', opts, function(err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function(item, cb) { - Person.create(item, cb); - }, function(err) { - if (err) { - // handle error - } - - // create and delete some data - const prom = Person.find({ age: { $lt: 1000 } }).exec(); - - prom.then(function(people) { - console.log('young people: %s', people); - }).then(cleanup); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/examples/schema/schema.js b/examples/schema/schema.js deleted file mode 100644 index be82788ae59..00000000000 --- a/examples/schema/schema.js +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Module dependencies. - */ - -'use strict'; - -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -/** - * Schema definition - */ - -// recursive embedded-document schema - -const Comment = new Schema(); - -Comment.add({ - title: { - type: String, - index: true - }, - date: Date, - body: String, - comments: [Comment] -}); - -const BlogPost = new Schema({ - title: { - type: String, - index: true - }, - slug: { - type: String, - lowercase: true, - trim: true - }, - date: Date, - buf: Buffer, - comments: [Comment], - creator: Schema.ObjectId -}); - -const Person = new Schema({ - name: { - first: String, - last: String - }, - email: { - type: String, - required: true, - index: { - unique: true, - sparse: true - } - }, - alive: Boolean -}); - -/** - * Accessing a specific schema type by key - */ - -BlogPost.path('date') - .default(function() { - return new Date(); - }) - .set(function(v) { - return v === 'now' ? new Date() : v; - }); - -/** - * Pre hook. - */ - -BlogPost.pre('save', function(next, done) { - /* global emailAuthor */ - emailAuthor(done); // some async function - next(); -}); - -/** - * Methods - */ - -BlogPost.methods.findCreator = function(callback) { - return this.db.model('Person').findById(this.creator, callback); -}; - -BlogPost.statics.findByTitle = function(title, callback) { - return this.find({ title: title }, callback); -}; - -BlogPost.methods.expressiveQuery = function(creator, date, callback) { - return this.find('creator', creator).where('date').gte(date).run(callback); -}; - -/** - * Plugins - */ - -function slugGenerator(options) { - options = options || {}; - const key = options.key || 'title'; - - return function slugGenerator(schema) { - schema.path(key).set(function(v) { - this.slug = v.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/-+/g, ''); - return v; - }); - }; -} - -BlogPost.plugin(slugGenerator()); - -/** - * Define model. - */ - -mongoose.model('BlogPost', BlogPost); -mongoose.model('Person', Person); diff --git a/examples/schema/storing-schemas-as-json/index.js b/examples/schema/storing-schemas-as-json/index.js deleted file mode 100644 index b20717d2ce6..00000000000 --- a/examples/schema/storing-schemas-as-json/index.js +++ /dev/null @@ -1,29 +0,0 @@ - -// modules -'use strict'; - -const mongoose = require('../../../lib'); -const Schema = mongoose.Schema; - -// parse json -const raw = require('./schema.json'); - -// create a schema -const timeSignatureSchema = Schema(raw); - -// compile the model -const TimeSignature = mongoose.model('TimeSignatures', timeSignatureSchema); - -// create a TimeSignature document -const threeFour = new TimeSignature({ - count: 3, - unit: 4, - description: '3/4', - additive: false, - created: new Date(), - links: ['http://en.wikipedia.org/wiki/Time_signature'], - user_id: '518d31a0ef32bbfa853a9814' -}); - -// print its description -console.log(threeFour); diff --git a/examples/schema/storing-schemas-as-json/schema.json b/examples/schema/storing-schemas-as-json/schema.json deleted file mode 100644 index 5afc626ccab..00000000000 --- a/examples/schema/storing-schemas-as-json/schema.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "count": "number", - "unit": "number", - "description": "string", - "links": ["string"], - "created": "date", - "additive": "boolean", - "user_id": "ObjectId" -} diff --git a/examples/statics/person.js b/examples/statics/person.js deleted file mode 100644 index 8af10c92c14..00000000000 --- a/examples/statics/person.js +++ /dev/null @@ -1,22 +0,0 @@ -// import the necessary modules -'use strict'; - -const mongoose = require('../../lib'); -const Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - const PersonSchema = new Schema({ - name: String, - age: Number, - birthday: Date - }); - - // define a static - PersonSchema.statics.findPersonByName = function(name, cb) { - this.find({ name: new RegExp(name, 'i') }, cb); - }; - - mongoose.model('Person', PersonSchema); -}; diff --git a/examples/statics/statics.js b/examples/statics/statics.js deleted file mode 100644 index b1e5aabb867..00000000000 --- a/examples/statics/statics.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; -const mongoose = require('../../lib'); - - -// import the schema -require('./person.js')(); - -// grab the person model object -const Person = mongoose.model('Person'); - -// connect to a server to do a quick write / read example -run().catch(console.error); - -async function run() { - await mongoose.connect('mongodb://127.0.0.1/persons'); - const bill = await Person.create({ - name: 'bill', - age: 25, - birthday: new Date().setFullYear((new Date().getFullYear() - 25)) - }); - console.log('People added to db: %s', bill.toString()); - - // using the static - const result = await Person.findPersonByName('bill'); - - console.log(result); - await cleanup(); -} - -async function cleanup() { - await Person.remove(); - mongoose.disconnect(); -}