1 |
|
2 | var path = require('path');
|
3 | var wrench = require('wrench');
|
4 | var mongoose = require('mongoose');
|
5 | var mongooseTypes = require('mongoose-types');
|
6 |
|
7 | exports.init = function(conf) {
|
8 | var connection = mongoose.createConnection(conf.url);
|
9 |
|
10 |
|
11 |
|
12 | var bson = require(__dirname + '/../node_modules/mongodb/node_modules/bson');
|
13 | mongoose.mongo.BinaryParser = bson.BinaryParser;
|
14 |
|
15 |
|
16 | mongooseTypes.loadTypes(mongoose);
|
17 |
|
18 |
|
19 |
|
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 |
|
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 |
|
40 | exports.create = function(model, props) {
|
41 | props = props || { };
|
42 |
|
43 |
|
44 | if (props.schema) {
|
45 | props.schema = new mongoose.Schema(props.schema);
|
46 | }
|
47 |
|
48 |
|
49 | if (props.useTimestamps) {
|
50 | props.schema.plugin(mongooseTypes.useTimestamps);
|
51 | }
|
52 |
|
53 |
|
54 | if (props.methods) {
|
55 | Object.keys(props.methods).forEach(function(i) {
|
56 | props.schema.methods[i] = props.methods[i];
|
57 | });
|
58 | }
|
59 |
|
60 |
|
61 | var model = connection.model(model, props.schema);
|
62 |
|
63 |
|
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 |
|
74 | exports.mongoose = mongoose;
|
75 | exports.types = mongoose.SchemaTypes;
|
76 |
|
77 |
|
78 | exports.init = undefined;
|
79 | });
|
80 |
|