Skip to content

Instantly share code, notes, and snippets.

@linuxsimba
Last active December 27, 2016 14:22
Show Gist options
  • Select an option

  • Save linuxsimba/ceee0c130222e4f2fd4fc87553ecebe6 to your computer and use it in GitHub Desktop.

Select an option

Save linuxsimba/ceee0c130222e4f2fd4fc87553ecebe6 to your computer and use it in GitHub Desktop.
Learning how to Use Generators with Mongoose
# Docker-compose for setting up Mongodb server on my laptop
version: '2'
networks:
mongodb_net:
driver: bridge
ipam:
driver: default
config:
- subnet: 192.168.213.0/24
gateway: 192.168.213.1
services:
mongodb:
image: mongo:latest
container_name: mongodb
networks:
- mongodb_net
ports:
- 27017:27017
{
"name": "es6-generator-mongoose-test",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"co": "^4.6.0",
"joi": "^10.1.0",
"mongoose": "^4.7.5",
"mongorito": "^2.2.0"
}
}
'use strict';
/**
* Dependencies
* From: https://github.com/vadimdemedes/mongorito/blob/master/examples/run.js (MIT)
*/
const co = require('co');
/**
* Run a generator function and print errors if any
*/
function run (fn) {
co(fn).catch(function (err) {
console.log(err.stack);
});
}
/**
* Expose fn
*/
module.exports = run;
'use strict';
/* Requirements:
node v6.3.0
npm install mongoose
npm install co
This test shows how to create a function that is a generator. Function where
you can use yield keywords.
*/
const mongoose = require('mongoose');
// Helper function for running generator functions using the 'co' package.
const run = require('./run');
// Change the Promise from the default mpromise which is deprecated
// to bluebird.
mongoose.Promise = require('bluebird');
const testme = function * () {
// connect to a database named "examples" on localhost
yield mongoose.connect('localhost/examples');
// connected
console.log('connected');
// and disconnect
yield mongoose.disconnect();
// disconnected
console.log('disconnected');
};
$ tree -L 1             
.
├── node_modules
├── package.json
├── run.js
└── server.js

1 directory, 3 files

$ node server.js
connected
disconnected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment