UNPKG

2.71 kBJavaScriptView Raw
1/*!
2 * Module dependencies.
3 */
4
5'use strict';
6
7const NodeJSDocument = require('./document');
8const EventEmitter = require('events').EventEmitter;
9const MongooseError = require('./error/index');
10const Schema = require('./schema');
11const ObjectId = require('./types/objectid');
12const ValidationError = MongooseError.ValidationError;
13const applyHooks = require('./helpers/model/applyHooks');
14const isObject = require('./helpers/isObject');
15
16/**
17 * Document constructor.
18 *
19 * @param {Object} obj the values to set
20 * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data
21 * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id
22 * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
23 * @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose.
24 * @event `save`: Emitted when the document is successfully saved
25 * @api private
26 */
27
28function Document(obj, schema, fields, skipId, skipInit) {
29 if (!(this instanceof Document)) {
30 return new Document(obj, schema, fields, skipId, skipInit);
31 }
32
33 if (isObject(schema) && !schema.instanceOfSchema) {
34 schema = new Schema(schema);
35 }
36
37 // When creating EmbeddedDocument, it already has the schema and he doesn't need the _id
38 schema = this.schema || schema;
39
40 // Generate ObjectId if it is missing, but it requires a scheme
41 if (!this.schema && schema.options._id) {
42 obj = obj || {};
43
44 if (obj._id === undefined) {
45 obj._id = new ObjectId();
46 }
47 }
48
49 if (!schema) {
50 throw new MongooseError.MissingSchemaError();
51 }
52
53 this.$__setSchema(schema);
54
55 NodeJSDocument.call(this, obj, fields, skipId, skipInit);
56
57 applyHooks(this, schema, { decorateDoc: true });
58
59 // apply methods
60 for (const m in schema.methods) {
61 this[m] = schema.methods[m];
62 }
63 // apply statics
64 for (const s in schema.statics) {
65 this[s] = schema.statics[s];
66 }
67}
68
69/*!
70 * Inherit from the NodeJS document
71 */
72
73Document.prototype = Object.create(NodeJSDocument.prototype);
74Document.prototype.constructor = Document;
75
76/*!
77 * ignore
78 */
79
80Document.events = new EventEmitter();
81
82/*!
83 * Browser doc exposes the event emitter API
84 */
85
86Document.$emitter = new EventEmitter();
87
88['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners',
89 'removeAllListeners', 'addListener'].forEach(function(emitterFn) {
90 Document[emitterFn] = function() {
91 return Document.$emitter[emitterFn].apply(Document.$emitter, arguments);
92 };
93});
94
95/*!
96 * Module exports.
97 */
98
99Document.ValidationError = ValidationError;
100module.exports = exports = Document;