1 |
|
2 |
|
3 |
|
4 |
|
5 | 'use strict';
|
6 |
|
7 | const NodeJSDocument = require('./document');
|
8 | const EventEmitter = require('events').EventEmitter;
|
9 | const MongooseError = require('./error/index');
|
10 | const Schema = require('./schema');
|
11 | const ObjectId = require('./types/objectid');
|
12 | const ValidationError = MongooseError.ValidationError;
|
13 | const applyHooks = require('./helpers/model/applyHooks');
|
14 | const isObject = require('./helpers/isObject');
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 | function Document(obj, schema, fields, skipId, skipInit) {
|
30 | if (!(this instanceof Document)) {
|
31 | return new Document(obj, schema, fields, skipId, skipInit);
|
32 | }
|
33 |
|
34 | if (isObject(schema) && !schema.instanceOfSchema) {
|
35 | schema = new Schema(schema);
|
36 | }
|
37 |
|
38 |
|
39 | schema = this.schema || schema;
|
40 |
|
41 |
|
42 | if (!this.schema && schema.options._id) {
|
43 | obj = obj || {};
|
44 |
|
45 | if (obj._id === undefined) {
|
46 | obj._id = new ObjectId();
|
47 | }
|
48 | }
|
49 |
|
50 | if (!schema) {
|
51 | throw new MongooseError.MissingSchemaError();
|
52 | }
|
53 |
|
54 | this.$__setSchema(schema);
|
55 |
|
56 | NodeJSDocument.call(this, obj, fields, skipId, skipInit);
|
57 |
|
58 | applyHooks(this, schema, { decorateDoc: true });
|
59 |
|
60 |
|
61 | for (const m in schema.methods) {
|
62 | this[m] = schema.methods[m];
|
63 | }
|
64 |
|
65 | for (const s in schema.statics) {
|
66 | this[s] = schema.statics[s];
|
67 | }
|
68 | }
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 | Document.prototype = Object.create(NodeJSDocument.prototype);
|
75 | Document.prototype.constructor = Document;
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 | Document.events = new EventEmitter();
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 | Document.$emitter = new EventEmitter();
|
88 |
|
89 | ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners',
|
90 | 'removeAllListeners', 'addListener'].forEach(function(emitterFn) {
|
91 | Document[emitterFn] = function() {
|
92 | return Document.$emitter[emitterFn].apply(Document.$emitter, arguments);
|
93 | };
|
94 | });
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 | Document.ValidationError = ValidationError;
|
101 | module.exports = exports = Document;
|