Files
meanTorrent/modules/articles/server/models/article.server.model.js
Michael Leanos eb9cdd784c feat(config): Mongo Seed 2.0 (#1808)
feat(config): Mongo Seed 2.0

Adds a more configurable and easily extended MongoDB Seed feature.

Adds additional options at the collection, and collection item level to
allow more control over how each environment config handles the seeding
feature.

Enforces seed order based on the order of the  environment's seeding configuration object.

Removes the previous SeedDB config file.

Adds chalk to messages logged to the console for readability.

Refactors the Mongo Seed configuration tests.

Adds Gulp tasks to perform Mongo Seed operations for default, prod, and
test environment configurations. Also, adds accommodating npm scripts.
2017-08-13 16:29:47 -07:00

139 lines
2.7 KiB
JavaScript

'use strict';
/**
* Module dependencies
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
path = require('path'),
config = require(path.resolve('./config/config')),
chalk = require('chalk');
/**
* Article Schema
*/
var ArticleSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
content: {
type: String,
default: '',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
ArticleSchema.statics.seed = seed;
mongoose.model('Article', ArticleSchema);
/**
* Seeds the User collection with document (Article)
* and provided options.
*/
function seed(doc, options) {
var Article = mongoose.model('Article');
return new Promise(function (resolve, reject) {
skipDocument()
.then(findAdminUser)
.then(add)
.then(function (response) {
return resolve(response);
})
.catch(function (err) {
return reject(err);
});
function findAdminUser(skip) {
var User = mongoose.model('User');
return new Promise(function (resolve, reject) {
if (skip) {
return resolve(true);
}
User
.findOne({
roles: { $in: ['admin'] }
})
.exec(function (err, admin) {
if (err) {
return reject(err);
}
doc.user = admin;
return resolve();
});
});
}
function skipDocument() {
return new Promise(function (resolve, reject) {
Article
.findOne({
title: doc.title
})
.exec(function (err, existing) {
if (err) {
return reject(err);
}
if (!existing) {
return resolve(false);
}
if (existing && !options.overwrite) {
return resolve(true);
}
// Remove Article (overwrite)
existing.remove(function (err) {
if (err) {
return reject(err);
}
return resolve(false);
});
});
});
}
function add(skip) {
return new Promise(function (resolve, reject) {
if (skip) {
return resolve({
message: chalk.yellow('Database Seeding: Article\t' + doc.title + ' skipped')
});
}
var article = new Article(doc);
article.save(function (err) {
if (err) {
return reject(err);
}
return resolve({
message: 'Database Seeding: Article\t' + article.title + ' added'
});
});
});
}
});
}