UNPKG

2.72 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} schema
21 * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data
22 * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id
23 * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
24 * @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose.
25 * @event `save`: Emitted when the document is successfully saved
26 * @api private
27 */
28
29function 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 // When creating EmbeddedDocument, it already has the schema and he doesn't need the _id
39 schema = this.schema || schema;
40
41 // Generate ObjectId if it is missing, but it requires a scheme
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 // apply methods
61 for (const m in schema.methods) {
62 this[m] = schema.methods[m];
63 }
64 // apply statics
65 for (const s in schema.statics) {
66 this[s] = schema.statics[s];
67 }
68}
69
70/*!
71 * Inherit from the NodeJS document
72 */
73
74Document.prototype = Object.create(NodeJSDocument.prototype);
75Document.prototype.constructor = Document;
76
77/*!
78 * ignore
79 */
80
81Document.events = new EventEmitter();
82
83/*!
84 * Browser doc exposes the event emitter API
85 */
86
87Document.$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 * Module exports.
98 */
99
100Document.ValidationError = ValidationError;
101module.exports = exports = Document;