├── .gitignore ├── Procfile ├── README.md ├── app.js ├── app.json └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | lib-cov 2 | *.seed 3 | *.log 4 | *.csv 5 | *.dat 6 | *.out 7 | *.pid 8 | *.gz 9 | 10 | .DS_Store 11 | 12 | pids 13 | logs 14 | results 15 | 16 | node_modules 17 | npm-debug.log 18 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: node app.js 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hello-mongoose: Using Mongoose.js for elegant MongoDB object modeling in Node.js. 2 | 3 | MongoDB and Node.js are often used together because of their shared use of Javascript and its Object Notation (JSON). Mongoose is a popular helper library that provides a more rigorous modeling environment for your data, enforcing a little bit more structure as needed, while still maintaining flexibility that makes MongoDB powerful. In this article, you make a connection to a hosted MongoDB instance at add-on provider [MongoLab](http://mongolab.com) with Mongoose and model a simple object. 4 | 5 | ## Deployment 6 | 7 | To deploy [the app](http://hello-mongoose.herokuapp.com/) to Heroku you can use the Heroku button [![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy) or follow these steps: 8 | 9 | 1. `git clone git://github.com/mongolab/hello-mongoose.git && cd hello-mongoose` 10 | 2. `heroku create` 11 | 3. `heroku addons:add mongolab` 12 | 3. `git push heroku master` 13 | 4. `heroku open` 14 | 15 | ## Docker 16 | 17 | The app can be debugged and tested using the [Heroku Docker CLI plugin](https://devcenter.heroku.com/articles/introduction-local-development-with-docker). 18 | 19 | Make sure the plugin is installed: 20 | 21 | heroku plugins:install heroku-docker 22 | 23 | Configure Docker and Docker Compose: 24 | 25 | heroku docker:init 26 | 27 | And run the app locally: 28 | 29 | docker-compose up 30 | 31 | The app will now be available on the Docker daemon IP on port 8080. 32 | 33 | You can also use Docker to release to Heroku: 34 | 35 | heroku create 36 | heroku docker:release 37 | heroku open 38 | 39 | ## License 40 | 41 | MIT Licensed 42 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | // 2 | // hello-mongoose: MongoDB with Mongoose on Node.js example on Heroku. 3 | // Mongoose is a object/data mapping utility for the MongoDB database. 4 | // 5 | 6 | // by Ben Wen with thanks to Aaron Heckmann 7 | 8 | // 9 | // Copyright 2015 ObjectLabs Corp. 10 | // ObjectLabs operates MongoLab.com a MongoDb-as-a-Service offering 11 | // 12 | // MIT Licensed 13 | // 14 | 15 | // Permission is hereby granted, free of charge, to any person 16 | // obtaining a copy of this software and associated documentation files 17 | // (the "Software"), to deal in the Software without restriction, 18 | // including without limitation the rights to use, copy, modify, merge, 19 | // publish, distribute, sublicense, and/or sell copies of the Software, 20 | // and to permit persons to whom the Software is furnished to do so, 21 | // subject to the following conditions: 22 | 23 | // The above copyright notice and this permission notice shall be 24 | // included in all copies or substantial portions of the Software. 25 | 26 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 27 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 28 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 29 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 30 | // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 31 | // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 32 | // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 33 | // SOFTWARE. 34 | 35 | // 36 | // Preamble 37 | var http = require ('http'); // For serving a basic web page. 38 | var mongoose = require ("mongoose"); // The reason for this demo. 39 | 40 | // Here we find an appropriate database to connect to, defaulting to 41 | // localhost if we don't find one. 42 | var uristring = 43 | process.env.MONGODB_URI || 44 | 'mongodb://localhost/HelloMongoose'; 45 | 46 | // The http server will listen to an appropriate port, or default to 47 | // port 5000. 48 | var theport = process.env.PORT || 5000; 49 | 50 | // Makes connection asynchronously. Mongoose will queue up database 51 | // operations and release them when the connection is complete. 52 | mongoose.connect(uristring, function (err, res) { 53 | if (err) { 54 | console.log ('ERROR connecting to: ' + uristring + '. ' + err); 55 | } else { 56 | console.log ('Succeeded connected to: ' + uristring); 57 | } 58 | }); 59 | 60 | // This is the schema. Note the types, validation and trim 61 | // statements. They enforce useful constraints on the data. 62 | var userSchema = new mongoose.Schema({ 63 | name: { 64 | first: String, 65 | last: { type: String, trim: true } 66 | }, 67 | age: { type: Number, min: 0} 68 | }); 69 | 70 | // Compiles the schema into a model, opening (or creating, if 71 | // nonexistent) the 'PowerUsers' collection in the MongoDB database 72 | var PUser = mongoose.model('PowerUsers', userSchema); 73 | 74 | // Clear out old data 75 | PUser.remove({}, function(err) { 76 | if (err) { 77 | console.log ('error deleting old data.'); 78 | } 79 | }); 80 | 81 | // Creating one user. 82 | var johndoe = new PUser ({ 83 | name: { first: 'John', last: 'Doe' }, 84 | age: 25 85 | }); 86 | 87 | // Saving it to the database. 88 | johndoe.save(function (err) {if (err) console.log ('Error on save!')}); 89 | 90 | // Creating more users manually 91 | var janedoe = new PUser ({ 92 | name: { first: 'Jane', last: 'Doe' }, 93 | age: 65 94 | }); 95 | janedoe.save(function (err) {if (err) console.log ('Error on save!')}); 96 | 97 | // Creating more users manually 98 | var alicesmith = new PUser ({ 99 | name: { first: 'Alice', last: 'Smith' }, 100 | age: 45 101 | }); 102 | alicesmith.save(function (err) {if (err) console.log ('Error on save!')}); 103 | 104 | 105 | // In case the browser connects before the database is connected, the 106 | // user will see this message. 107 | var found = ['DB Connection not yet established. Try again later. Check the console output for error messages if this persists.']; 108 | 109 | // Create a rudimentary http server. (Note, a real web application 110 | // would use a complete web framework and router like express.js). 111 | // This is effectively the main interaction loop for the application. 112 | // As new http requests arrive, the callback function gets invoked. 113 | http.createServer(function (req, res) { 114 | res.writeHead(200, {'Content-Type': 'text/html'}); 115 | createWebpage(req, res); 116 | }).listen(theport); 117 | 118 | function createWebpage (req, res) { 119 | // Let's find all the documents 120 | PUser.find({}).exec(function(err, result) { 121 | if (!err) { 122 | res.write(html1 + JSON.stringify(result, undefined, 2) + html2 + result.length + html3); 123 | // Let's see if there are any senior citizens (older than 64) with the last name Doe using the query constructor 124 | var query = PUser.find({'name.last': 'Doe'}); // (ok in this example, it's all entries) 125 | query.where('age').gt(64); 126 | query.exec(function(err, result) { 127 | if (!err) { 128 | res.end(html4 + JSON.stringify(result, undefined, 2) + html5 + result.length + html6); 129 | } else { 130 | res.end('Error in second query. ' + err) 131 | } 132 | }); 133 | } else { 134 | res.end('Error in first query. ' + err) 135 | }; 136 | }); 137 | } 138 | 139 | // Tell the console we're getting ready. 140 | // The listener in http.createServer should still be active after these messages are emitted. 141 | console.log('http server will be listening on port %d', theport); 142 | console.log('CTRL+C to exit'); 143 | 144 | // 145 | // House keeping. 146 | 147 | // 148 | // The rudimentary HTML content in three pieces. 149 | var html1 = ' hello-mongoose: MongoLab MongoDB Mongoose Node.js Demo on Heroku \ 150 | \ 151 | \ 152 | \ 153 | \ 154 |

hello-mongoose: MongoLab MongoDB Mongoose Node.js Demo on Heroku

\ 155 | See the supporting article on the Dev Center to learn more about data modeling with Mongoose. \ 156 | \ 157 | \ 158 |

All Documents in MonogoDB database

 ';
159 | var html2 = '
'; 160 | var html3 = ' documents. '; 161 | var html4 = '

Queried (name.last = "Doe", age >64) Documents in MonogoDB database

 ';
162 | var html5 = '
'; 163 | var html6 = ' documents. \ 164 |
Demo code available at github.com
'; 165 | 166 | 167 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hello-mongoose", 3 | "description": "MongoDB with Mongoose on Node.js example", 4 | "image": "heroku/nodejs", 5 | "repository": "https://github.com/mongolab/hello-mongoose.git", 6 | "keywords": ["node", "mongoose", "ODM"], 7 | "addons": ["mongolab"] 8 | } 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hello-mongoose", 3 | "version": "0.3.0", 4 | "description": "MongoDB with Mongoose on Node.js example", 5 | "main": "app.js", 6 | "engines" : { 7 | "node" : ">=4.1.1", 8 | "npm" : ">=2.1.x" 9 | }, 10 | "repository": "https://github.com/mongolab/hello-mongoose.git", 11 | "authors": [ "Ben Wen", "Chris Chang" ], 12 | "license": "MIT", 13 | "dependencies": { 14 | "mongoose": ">=4.1.11" 15 | }, 16 | "changelog" : [{"0.0.0": "Initial release"}, 17 | {"0.1.0": "Update to Mongoose 3.5.7; new MongoClient semantics"}, 18 | {"0.2.0": "Update to Mongoose 3.8.15; updated Node engine to 0.10.31; updated npm engine to >=1.4"}, 19 | {"0.3.0": "Update to Mongoose >=4.1.11; updated Node engine to >=4.1.1; updated npm engine to >=2.1.x"}], 20 | "homepage" : "http://hello-mongoose.herokuapp.com" 21 | } 22 | 23 | --------------------------------------------------------------------------------