Skip to content

Instantly share code, notes, and snippets.

@DigitalLeaves
Last active May 17, 2019 03:56
Show Gist options
  • Save DigitalLeaves/06b514f19ef43e74b5979f6e0d099440 to your computer and use it in GitHub Desktop.
Save DigitalLeaves/06b514f19ef43e74b5979f6e0d099440 to your computer and use it in GitHub Desktop.
/*********** database.js ******************/
var mongoose = require('mongoose')
mongoose.Promise = global.Promise
mongoose.set('useFindAndModify', false)
// connection
exports.connection = null
// schemas and entities
exports.User = null
exports.UserSchema = null
// Connect to database
exports.connectToDatabase = function () {
if (!exports.connection) {
var db = mongoose.createConnection('mongodb://localhost:27017/databasename', { useNewUrlParser: true })
mongoose.set('useCreateIndex', true)
exports.connection = db
exports.defineDatabaseSchemas()
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
if (exports.connection) { exports.connection.close(function () { exports.connection = null; }); }
})
// If the Node process exits, close the Mongoose connection
process.on('exit', function() {
if (exports.connection) { exports.connection.close(function () { exports.connection = null; }); }
})
}
}
exports.currentConnection = function() { return exports.connection }
exports.closeConnection = function(completion) {
if (exports.connection) {
exports.connection.close(function () {
exports.connection = null
if (completion) { completion() }
})
} else { if (completion) { completion() } }
}
exports.defineDatabaseSchemas = function () {
console.log(env.name+" database: Defining global database schemas")
// Users
var userSchema = mongoose.Schema({
"first_name": { type: String, required: true },
"last_name": { type: String, required: true },
"locale": String,
"status": String,
"bio": String,
"login_key": String,
"email": String,
"promo_code": String,
"phone": String,
"avatar": String,
"certificate": {
"_id": false,
"text": String,
"properties": mongoose.Schema.Types.Mixed,
"signature_algorithm": String,
"start_date": Date,
"end_date": Date
},
"registration_data": mongoose.Schema.Types.Mixed,
"created": Date,
"heard_about_us": String, // where did you hear about us?
})
exports.User = exports.connection.model('users', userSchema)
exports.UserSchema = userSchema
}
/*********** test.js ******************/
var db = require('./database.js')
db.connectToDatabase()
var newUser = new db.User({
"first_name": "John",
"last_name": "Smith",
"email": "[email protected]",
"phone": "+1233489548",
})
newUser.save(function (err, savedUser) {
console.log(err)
console.log(savedUser)
db.closeConnection()
console.log("Exiting...")
process.exit(0)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment