Es6 static call non static hướng dẫn
If you haven't yet done so, please take a minute to read the quickstart to get an idea of how Mongoose works. If you are migrating from 7.x to 8.x please take a moment to read the migration guide. Show Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
If you want to add additional keys later, use the method. Each key in our code
6 defines a property in our documents which will be cast to its associated . For example, we've defined a property
7 which will be cast to the SchemaType and property
8 which will be cast to a
9 SchemaType. Notice above that if a property only requires a type, it can be specified using a shorthand notation (contrast the
7 property above with the
8 property). Keys may also be assigned nested objects containing further key/type definitions like the
2 property above. This will happen whenever a key's value is a POJO that doesn't have a
3 property. In these cases, Mongoose only creates actual schema paths for leaves in the tree. (like
4 and
5 above), and the branches do not have actual paths. A side-effect of this is that
2 above cannot have its own validation. If validation is needed up the tree, a path needs to be created up the tree - see the Subdocuments section for more information on how to do this. Also read the Mixed subsection of the SchemaTypes guide for some gotchas. The permitted SchemaTypes are: Read more about SchemaTypes here. Schemas not only define the structure of your document and casting of properties, they also define document , , , and document lifecycle hooks called middleware. To use our schema definition, we need to convert our
6 into a Model we can work with. To do so, we pass it into
8:
By default, Mongoose adds an
9 property to your schemas.
When you create a new document with the automatically added
9 property, Mongoose creates a new
9 of type ObjectId to your document.
You can also overwrite Mongoose's default
9 with your own
9. Just be careful: Mongoose will refuse to save a document that doesn't have an
9, so you're responsible for setting
9 if you define your own
9 path.
Instances of
7 are documents. Documents have many of their own built-in instance methods. We may also define our own custom document instance methods.
Now all of our
8 instances have a
9 method available to them.
You can also add static functions to your model. There are three equivalent ways to add a static:
Do not declare statics using ES6 arrow functions (
02). Arrow functions , so the above examples will not work because of the value of
03. You can also add query helper functions, which are like instance methods but for mongoose queries. Query helper methods let you extend mongoose's chainable query builder API.
MongoDB supports secondary indexes. With mongoose, we define these indexes within our
10 or the
11 level. Defining indexes at the schema level is necessary when creating compound indexes.
See for other index options. When your application starts up, Mongoose automatically calls for each defined index in your schema. Mongoose will call
12 for each index sequentially, and emit an 'index' event on the model when all the
12 calls succeeded or when there was an error. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a . Disable the behavior by setting the
15 option of your schema to
16, or globally on the connection by setting the option
15 to
16.
0 Mongoose will emit an
19 event on the model when indexes are done building or an error occurred.
1 See also the method. are document properties that you can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combining fields, while setters are useful for de-composing a single value into multiple values for storage.
2 Suppose you want to print out the person's full name. You could do it yourself:
3 But concatenating the first and last name every time can get cumbersome. And what if you want to do some extra processing on the name, like removing diacritics? A lets you define a
20 property that won't get persisted to MongoDB.
4 Now, mongoose will call your getter function every time you access the
20 property:
5 If you use
22 or
23 Mongoose will not include virtuals by default. Pass
24 to or
23 to include virtuals.
6 The above caveat for
22 also includes the output of calling
28 on a Mongoose document, because . To include virtuals in
28 output, you can either call
32 on the document before calling
28, or set the
34 option on your schema.
7 You can also add a custom setter to your virtual that will let you set both first name and last name via the
20 virtual.
8 Virtual property setters are applied before other validation. So the example above would still work even if the
36 and
37 name fields were required. Only non-virtual properties work as part of queries and for field selection. Since virtuals are not stored in MongoDB, you can't query with them. You can learn more about virtuals here. Aliases are a particular type of virtual where the getter and setter seamlessly get and set another property. This is handy for saving network bandwidth, so you can convert a short property name stored in the database into a longer name for code readability.
9 You can also declare aliases on nested paths. It is easier to use nested schemas and subdocuments, but you can also declare nested path aliases inline as long as you use the full nested path
38 as the alias.
0 Schemas have a few configurable options which can be passed to the constructor or to the
39 method:
1 Valid options: By default, Mongoose's creates all the indexes defined in your model's schema by calling after you successfully connect to MongoDB. Creating indexes automatically is great for development and test environments. But index builds can also create significant load on your production database. If you want to manage indexes carefully in production, you can set
15 to false.
2 The
15 option is set to
44 by default. You can change this default by setting Before Mongoose builds indexes, it calls
46 to create the underlying collection in MongoDB by default. Calling
47 sets the collection's default collation based on the and establishes the collection as a capped collection if you set the . You can disable this behavior by setting
49 to
16 using . Like
15,
49 is helpful for development and test environments, but you may want to disable it for production to avoid unnecessary database calls. Unfortunately,
47 cannot change an existing collection. For example, if you add
55 to your schema and the existing collection is not capped,
47 will not overwrite the existing collection. That is because the MongoDB server does not allow changing a collection's options without dropping the collection first.
3 By default, mongoose buffers commands when the connection goes down until the driver manages to reconnect. To disable buffering, set
57 to false.
4 The schema
57 option overrides the global
57 option.
5 If
57 is on, this option sets the maximum amount of time Mongoose buffering will wait before throwing an error. If not specified, Mongoose will use 10000 (10 seconds).
6 Mongoose supports MongoDBs capped collections. To specify the underlying MongoDB collection be
48, set the
48 option to the maximum size of the collection in .
7 The
48 option may also be set to an object if you want to pass additional options like . In this case you must explicitly pass the
64 option, which is required.
8 Mongoose by default produces a collection name by passing the model name to the
65 method. This method pluralizes the name. Set this option if you need a different name for your collection.
9 When you define a discriminator, Mongoose adds a path to your schema that stores which discriminator a document is an instance of. By default, Mongoose adds an
66 path, but you can set
67 to overwrite this default.
0 When
68 is
44, Mongoose will not create indexes from the given subdocument schema. This option only works when the schema is used in a subdocument path or document array path, Mongoose ignores this option if set on the top-level schema for a model. Defaults to
16.
1 Mongoose assigns each of your schemas an
71 virtual getter by default which returns the document's
9 field cast to a string, or in the case of ObjectIds, its hexString. If you don't want an
71 getter added to your schema, you may disable it by passing this option at schema construction time.
2 Mongoose assigns each of your schemas an
9 field by default if one is not passed into the constructor. The type assigned is an to coincide with MongoDB's default behavior. If you don't want an
9 added to your schema at all, you may disable it using this option. You can only use this option on subdocuments. Mongoose can't save a document without knowing its id, so you will get an error if you try to save a document without an
9.
3 Mongoose will, by default, "minimize" schemas by removing empty objects.
4 This behavior can be overridden by setting
77 option to
16. It will then store empty objects.
5 To check whether an object is empty, you can use the
79 helper:
6 Allows setting options at the schema level, providing us a way to apply default to all queries derived from a model.
7 The alias of each pref is also permitted so instead of having to type out 'secondaryPreferred' and getting the spelling wrong, we can simply pass 'sp'. The read option also allows us to specify tag sets. These tell the driver from which members of the replica-set it should attempt to read. Read more about tag sets and here. NOTE: you may also specify the driver read preference option when connecting:
8 Allows setting write concern at the schema level.
9 The
80 option is used when we have a sharded MongoDB architecture. Each sharded collection is given a shard key which must be present in all insert/update operations. We just need to set this schema option to the same shard key and we’ll be all set.
0 Note that Mongoose does not send the
81 command for you. You must configure your shards yourself. The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db.
1 This also affects the use of
82 to set a property value.
2 This value can be overridden at the model instance level by passing a second boolean argument:
3 The
83 option may also be set to
84 which will cause errors to be produced instead of dropping the bad data. NOTE: Any key/val set on the instance that does not exist in your schema is always ignored, regardless of schema option.
4 Mongoose supports a separate
85 option to avoid strict mode for query filters. This is because empty query filters cause Mongoose to return all documents in the model, which can cause issues.
5 The
83 option does apply to updates. The
85 option is just for query filters.
6 Mongoose has a separate
85 option to toggle strict mode for the
89 parameter to queries.
7 In general, we do not recommend passing user-defined objects as query filters:
8 In Mongoose 7,
85 is
16 by default. However, you can override this behavior globally:
9 Exactly the same as the option but only applies when the document's
92 method is called.
0 To see all available
93 options, read . Documents have a method which converts the mongoose document into a plain JavaScript object. This method accepts a few options. Instead of applying these options on a per-document basis, we may declare the options at the schema level and have them applied to all of the schema's documents by default. To have all virtuals show up in your
94 output, set the
95 option to
96:
1 To see all available
95 options, read . By default, if you have an object with key 'type' in your schema, mongoose will interpret it as a type declaration.
2 However, for applications like geoJSON, the 'type' property is important. If you want to control which key mongoose uses to find type declarations, set the 'typeKey' schema option.
3 By default, documents are automatically validated before they are saved to the database. This is to prevent saving an invalid document. If you want to handle validation manually, and be able to save objects which don't pass validation, you can set
98 to false.
4 The
99 is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The
99 option is a string that represents the path to use for versioning. The default is
01. If this conflicts with your application you can configure as such:
5 Note that Mongoose's default versioning is not a full optimistic concurrency solution. Mongoose's default versioning only operates on arrays as shown below.
6 If you need optimistic concurrency support for
02, you can set the Document versioning can also be disabled by setting the
99 to
16. DO NOT disable versioning unless you know what you are doing.
7 Mongoose only updates the version key when you use . If you use
07,
08, etc. Mongoose will not update the version key. As a workaround, you can use the below middleware.
8 Optimistic concurrency is a strategy to ensure the document you're updating didn't change between when you loaded it using
09 or
10, and when you update it using
02. For example, suppose you have a
12 model that contains a list of
13, and a
14 that represents whether this house shows up in searches. Suppose that a house that has status
15 must have at least two
13. You might implement the logic of approving a house document as shown below:
9 The
17 function looks right in isolation, but there might be a potential issue: what if another function removes the house's photos between the
10 call and the
02 call? For example, the below code will succeed:
0 If you set the
03 option on the
12 model's schema, the above script will throw an error.
1 Sets a default collation for every query and aggregation. Here's a beginner-friendly overview of collations.
2 If you set the
22 option on a schema, Mongoose will create a timeseries collection for any model that you create from that schema.
3
23 allows excluding paths from versioning (i.e., the internal revision will not be incremented even if these paths are updated). DO NOT do this unless you know what you're doing. For subdocuments, include this on the parent document using the fully qualified path.
4 The
24 option tells Mongoose to assign
25 and
26 fields to your schema. The type assigned is . By default, the names of the fields are
25 and
26. Customize the field names by setting
29 and
30. The way
24 works under the hood is:
5 By default, Mongoose uses
40 to get the current time. If you want to overwrite the function Mongoose uses to get the current time, you can set the
41 option. Mongoose will call the
41 function whenever it needs to get the current time.
6 Mongoose supports defining global plugins, plugins that apply to all schemas.
7 Sometimes, you may only want to apply a given plugin to some schemas. In that case, you can add
43 to a schema:
8 If you call
44 with a
45 option, Mongoose will only apply that plugin to schemas that have a matching entry in
43.
9 By default, Mongoose will automatically
47 any populated paths for you, unless you explicitly exclude them.
0 To opt out of selecting populated fields by default, set
48 to
16 in your schema.
1 For legacy reasons, when there is a validation error in subpath of a single nested schema, Mongoose will record that there was a validation error in the single nested schema path as well. For example:
2 Set the
50 to
16 on the child schema to make Mongoose only reports the parent error.
3 Options like and affect the options Mongoose passes to MongoDB when creating a new collection. Mongoose schemas support most MongoDB
47 options, but not all. You can use the
55 option to set any
47 options; Mongoose will use
55 as the default values when calling
47 for your schema.
4 Schemas have a that you can use to create a Mongoose schema from an ES6 class:
Here's an example of using
59 to create a schema from an ES6 class:
5 Schemas are also pluggable which allows us to package up reusable features into plugins that can be shared with the community or just between your projects. Here's an alternative introduction to Mongoose schemas. To get the most out of MongoDB, you need to learn the basics of MongoDB schema design. SQL schema design (third normal form) was designed to minimize storage costs, whereas MongoDB schema design is about making common queries as fast as possible. The 6 Rules of Thumb for MongoDB Schema Design blog series is an excellent resource for learning the basic rules for making your queries fast. Users looking to master MongoDB schema design in Node.js should look into The Little MongoDB Schema Design Book by Christian Kvalheim, the original author of the MongoDB Node.js driver. This book shows you how to implement performant schemas for a laundry list of use cases, including e-commerce, wikis, and appointment bookings. |