UNPKG

2.2 kBJavaScriptView Raw
1
2var path = require('path');
3var wrench = require('wrench');
4var mongoose = require('mongoose');
5var mongooseTypes = require('mongoose-types');
6
7exports.init = function(conf) {
8 var connection = mongoose.createConnection(conf.url);
9
10 // Patch mongoose-types bug (#17 and #21)
11 // @link {https://github.com/bnoguchi/mongoose-types/}
12 var bson = require(__dirname + '/../node_modules/mongodb/node_modules/bson');
13 mongoose.mongo.BinaryParser = bson.BinaryParser;
14
15 // Load mongoose-types extension
16 mongooseTypes.loadTypes(mongoose);
17
18 // Find all of the models (This does not load models,
19 // simply creates a registry with all of the file paths)
20 var models = { };
21 wrench.readdirSyncRecursive(conf.modelPath).forEach(function(file) {
22 if (file[0] === '.') {return;}
23 file = file.split('.');
24 if (file.length > 1 && file.pop() === 'js') {
25 file = file.join('.');
26 file = path.join(modelPath, file);
27 models[path.basename(file)] = file;
28 }
29 });
30
31 // Load a model
32 exports.require = function(model) {
33 if (typeof models[model] === 'string') {
34 models[model] = require(models[model]);
35 }
36 return models[model];
37 };
38
39 // Creates a new model
40 exports.create = function(model, props) {
41 props = props || { };
42
43 // Check for a scheme definition
44 if (props.schema) {
45 props.schema = new mongoose.Schema(props.schema);
46 }
47
48 // Check if we are loading the timestamps plugin
49 if (props.useTimestamps) {
50 props.schema.plugin(mongooseTypes.useTimestamps);
51 }
52
53 // Bind any instance methods to the schema.methods object
54 if (props.methods) {
55 Object.keys(props.methods).forEach(function(i) {
56 props.schema.methods[i] = props.methods[i];
57 });
58 }
59
60 // Create the mongoose model
61 var model = connection.model(model, props.schema);
62
63 // Copy over all other properties as static model properties
64 Object.keys(props).forEach(function(i) {
65 if (i !== 'schema' && i !== 'useTimestamps' && i !== 'methods') {
66 model[i] = props[i];
67 }
68 });
69
70 return model;
71 };
72
73 // Expose mongoose and mongoose's types
74 exports.mongoose = mongoose;
75 exports.types = mongoose.SchemaTypes;
76
77 // Don't allow re-init
78 exports.init = undefined;
79});
80