From 1a2d7f8956728d3e322279571e3cff4c36cdfb8e Mon Sep 17 00:00:00 2001 From: hasezoey Date: Mon, 14 Nov 2022 14:32:26 +0100 Subject: [PATCH 1/4] chore(gitignore): use gitignore from current master --- .gitignore | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 361b203fffb..d84960d7861 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ benchmarks/benchmarks benchmarks/benchmarks2 benchmarks/benchmarks3 benchmarks/v8.log +benchmarks/typescript/**/*.js .DS_Store docs/*.json docs/source/_docs @@ -40,11 +41,23 @@ test/files/main.js package-lock.json -.config* +.config.js # Compiled docs docs/*.html docs/tutorials/*.html docs/typescript/*.html docs/api/*.html -index.html \ No newline at end of file +index.html + +# Local Netlify folder +.netlify + +# yarn package-lock +yarn.lock + +# npm pack output +mongoose.tgz +mongoose-*.tgz + +examples/ecommerce-netlify-functions/.netlify/state.json From 9ca46d11ecfadc17f49b84f3601538d032896f59 Mon Sep 17 00:00:00 2001 From: hasezoey Date: Mon, 14 Nov 2022 14:35:20 +0100 Subject: [PATCH 2/4] docs: backport static links to relative re #12690 --- docs/deprecations.md | 4 ++-- docs/jest.md | 4 ++-- docs/promises.md | 4 ++-- docs/queries.md | 2 +- docs/tutorials/custom-casting.md | 4 ++-- docs/tutorials/getters-setters.md | 4 ++-- docs/tutorials/query_casting.md | 8 ++++---- 7 files changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/deprecations.md b/docs/deprecations.md index b17953659c0..628c304fca1 100644 --- a/docs/deprecations.md +++ b/docs/deprecations.md @@ -101,7 +101,7 @@ behavior until Mongoose 6.0.

ensureIndex()

-If you define [indexes in your Mongoose schemas](https://mongoosejs.com/docs/guide.html#indexes), you'll see the below +If you define [indexes in your Mongoose schemas](guide.html#indexes), you'll see the below deprecation warning. ``` @@ -290,4 +290,4 @@ const writeStream = gfs.createWriteStream({ filename: 'test.dat' }); const conn = mongoose.createConnection('mongodb://localhost:27017/gfstest'); const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db); const writeStream = gridFSBucket.openUploadStream('test.dat'); -``` \ No newline at end of file +``` diff --git a/docs/jest.md b/docs/jest.md index 36e07845d45..108ca6efcd0 100644 --- a/docs/jest.md +++ b/docs/jest.md @@ -8,7 +8,7 @@ If you choose to delve into dangerous waters and test Mongoose apps with Jest, h -If you are using Jest `<=26`, do **not** use Jest's default [`jsdom` test environment](https://jestjs.io/docs/en/configuration.html#testenvironment-string) when testing Mongoose apps, _unless_ you are explicitly testing an application that only uses [Mongoose's browser library](https://mongoosejs.com/docs/browser.html). In Jest `>=27`, ["node" is Jest's default `testEnvironment`](https://jestjs.io/ro/blog/2021/05/25/jest-27#flipping-defaults), so this is no longer an issue. +If you are using Jest `<=26`, do **not** use Jest's default [`jsdom` test environment](https://jestjs.io/docs/en/configuration.html#testenvironment-string) when testing Mongoose apps, _unless_ you are explicitly testing an application that only uses [Mongoose's browser library](browser.html). In Jest `>=27`, ["node" is Jest's default `testEnvironment`](https://jestjs.io/ro/blog/2021/05/25/jest-27#flipping-defaults), so this is no longer an issue. The `jsdom` test environment attempts to create a browser-like test environment in Node.js, and it comes with numerous nasty surprises like a @@ -81,4 +81,4 @@ course on Pluralsight has a great section on testing Mongoose apps with [Mocha]( - \ No newline at end of file + diff --git a/docs/promises.md b/docs/promises.md index 562626890a3..cc86b1e602f 100644 --- a/docs/promises.md +++ b/docs/promises.md @@ -7,7 +7,7 @@ This means that you can do things like `MyModel.findOne({}).then()` and `await MyModel.findOne({}).exec()` if you're using [async/await](http://thecodebarbarian.com/80-20-guide-to-async-await-in-node.js.html). -You can find the return type of specific operations [in the api docs](https://mongoosejs.com/docs/api.html) +You can find the return type of specific operations [in the api docs](api.html) You can also read more about [promises in Mongoose](https://masteringjs.io/tutorials/mongoose/promise). ```javascript @@ -72,4 +72,4 @@ ES6-style promise constructor and mongoose will use it.

- \ No newline at end of file + diff --git a/docs/queries.md b/docs/queries.md index 501fe37068f..f1ee795559c 100644 --- a/docs/queries.md +++ b/docs/queries.md @@ -200,7 +200,7 @@ of inactivity. You can read more about working around session idle timeouts in t

Versus Aggregation

-[Aggregation](https://mongoosejs.com/docs/api.html#aggregate_Aggregate) can +[Aggregation](api.html#aggregate_Aggregate) can do many of the same things that queries can. For example, below is how you can use `aggregate()` to find docs where `name.last = 'Ghost'`: diff --git a/docs/tutorials/custom-casting.md b/docs/tutorials/custom-casting.md index 8a60dc2630b..9c1d12aac3a 100644 --- a/docs/tutorials/custom-casting.md +++ b/docs/tutorials/custom-casting.md @@ -1,6 +1,6 @@ # Custom Casting -[Mongoose 5.4.0](https://github.com/Automattic/mongoose/blob/master/History.md#540--2018-12-14) introduced [several ways to configure SchemaTypes globally](http://thecodebarbarian.com/whats-new-in-mongoose-54-global-schematype-configuration). One of these new features is the [`SchemaType.cast()` function](https://mongoosejs.com/docs/api.html#schematype_SchemaType-cast), which enables you to override Mongoose's built-in casting. +[Mongoose 5.4.0](https://github.com/Automattic/mongoose/blob/master/History.md#540--2018-12-14) introduced [several ways to configure SchemaTypes globally](http://thecodebarbarian.com/whats-new-in-mongoose-54-global-schematype-configuration). One of these new features is the [`SchemaType.cast()` function](../api.html#schematype_SchemaType-cast), which enables you to override Mongoose's built-in casting. For example, by default Mongoose will throw an error if you attempt to cast a string that contains a Japanese numeral to a number. @@ -14,4 +14,4 @@ the string that contains the Japanese numeral "2" to a number as shown below. ```javascript [require:custom casting.*casting override] -``` \ No newline at end of file +``` diff --git a/docs/tutorials/getters-setters.md b/docs/tutorials/getters-setters.md index 044ca0ea406..c26606db0e1 100644 --- a/docs/tutorials/getters-setters.md +++ b/docs/tutorials/getters-setters.md @@ -26,7 +26,7 @@ app.get(function(req, res) { }); ``` -To disable running getters when converting a document to JSON, set the [`toJSON.getters` option to `false` in your schema](https://mongoosejs.com/docs/guide.html#toJSON) as shown below. +To disable running getters when converting a document to JSON, set the [`toJSON.getters` option to `false` in your schema](../guide.html#toJSON) as shown below. ```javascript const userSchema = new Schema({ @@ -80,4 +80,4 @@ corresponding getter for `email`. ```javascript [require:getters/setters.*setters.*vs ES6] -``` \ No newline at end of file +``` diff --git a/docs/tutorials/query_casting.md b/docs/tutorials/query_casting.md index 0ce03a09902..01c06c9a509 100644 --- a/docs/tutorials/query_casting.md +++ b/docs/tutorials/query_casting.md @@ -1,12 +1,12 @@ # Query Casting -The first parameter to [`Model.find()`](https://mongoosejs.com/docs/api.html#model_Model.find), [`Query#find()`](https://mongoosejs.com/docs/api.html#query_Query-find), [`Model.findOne()`](https://mongoosejs.com/docs/api.html#model_Model.findOne), etc. is called `filter`. In older content this parameter is sometimes called `query` or `conditions`. For example: +The first parameter to [`Model.find()`](../api.html#model_Model.find), [`Query#find()`](../api.html#query_Query-find), [`Model.findOne()`](../api.html#model_Model.findOne), etc. is called `filter`. In older content this parameter is sometimes called `query` or `conditions`. For example: ```javascript [require:Cast Tutorial.*get and set] ``` -When you execute the query using [`Query#exec()`](https://mongoosejs.com/docs/api.html#query_Query-exec) or [`Query#then()`](https://mongoosejs.com/docs/api.html#query_Query-then), Mongoose _casts_ the filter to match your schema. +When you execute the query using [`Query#exec()`](../api.html#query_Query-exec) or [`Query#then()`](../api.html#query_Query-then), Mongoose _casts_ the filter to match your schema. ```javascript [require:Cast Tutorial.*cast values] @@ -27,7 +27,7 @@ By default, Mongoose does **not** cast filter properties that aren't in your sch [require:Cast Tutorial.*not in schema] ``` -You can configure this behavior using the [`strictQuery` option for schemas](https://mongoosejs.com/docs/guide.html#strictQuery). This option is analogous to the [`strict` option](https://mongoosejs.com/docs/guide.html#strict). Setting `strictQuery` to `true` removes non-schema properties from the filter: +You can configure this behavior using the [`strictQuery` option for schemas](../guide.html#strictQuery). This option is analogous to the [`strict` option](../guide.html#strict). Setting `strictQuery` to `true` removes non-schema properties from the filter: ```javascript [require:Cast Tutorial.*strictQuery true] @@ -46,4 +46,4 @@ Because of schemas, Mongoose knows what types fields should be, so it can provid ```javascript [require:Cast Tutorial.*implicit in] -``` \ No newline at end of file +``` From 8b306eb0dec95e6a1f7869264c913f44ca5f2734 Mon Sep 17 00:00:00 2001 From: hasezoey Date: Mon, 14 Nov 2022 14:44:39 +0100 Subject: [PATCH 3/4] docs: change relative links to no-prefix links re #12690 --- docs/async-await.md | 6 ++--- docs/connections.md | 10 +++---- docs/documents.md | 8 +++--- docs/faq.md | 14 +++++----- docs/guide.md | 64 ++++++++++++++++++++++----------------------- docs/middleware.md | 42 ++++++++++++++--------------- docs/models.md | 18 ++++++------- docs/populate.md | 18 ++++++------- docs/queries.md | 16 ++++++------ docs/schematypes.md | 40 ++++++++++++++-------------- docs/subdocs.md | 18 ++++++------- docs/validation.md | 24 ++++++++--------- 12 files changed, 139 insertions(+), 139 deletions(-) diff --git a/docs/async-await.md b/docs/async-await.md index d68616299f4..fdc223e060e 100644 --- a/docs/async-await.md +++ b/docs/async-await.md @@ -62,7 +62,7 @@ async function awaitUpdate() { } ``` -Note that the specific fulfillment values of different Mongoose methods vary, and may be affected by configuration. Please refer to the [API documentation](./api.html) for information about specific methods. +Note that the specific fulfillment values of different Mongoose methods vary, and may be affected by configuration. Please refer to the [API documentation](api.html) for information about specific methods. ### Async Functions @@ -108,7 +108,7 @@ Under the hood, [async/await is syntactic sugar](https://developer.mozilla.org/e Due to the surprisingly simple way promises are implemented in JavaScript, the keyword `await` will try to unwrap any object with a property whose key is the string ‘then’ and whose value is a function. Such objects belong to a broader class of objects called [thenables](https://masteringjs.io/tutorials/fundamentals/thenable). If the thenable being unwrapped is a genuine promise, e.g. an instance of the [Promise constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), we enjoy several guarantees about how the object’s ‘then’ function will behave. -However, Mongoose provides several static helper methods that return a different class of thenable object called a [Query](./queries.html)--and [Queries are not promises](./queries.html#queries-are-not-promises). +However, Mongoose provides several static helper methods that return a different class of thenable object called a [Query](queries.html)--and [Queries are not promises](queries.html#queries-are-not-promises). Because Queries are also *thenables*, we can interact with a Query using async/await just as we would interact with a genuine promise, with one key difference: observing the fulfillment value of a genuine promise cannot under any circumstances change that value, but trying to re-observe the value of a Query may cause the Query to be re-executed. ```javascript @@ -148,4 +148,4 @@ async function observeQuery() { You are most likely to accidentally re-execute queries in this way when mixing callbacks with async/await. This is never necessary and should be avoided. - If you need a Query to return a fully-fleged promise instead of a thenable, you can use [Query#exec()](./api/query.html#query_Query-exec). \ No newline at end of file + If you need a Query to return a fully-fleged promise instead of a thenable, you can use [Query#exec()](api/query.html#query_Query-exec). diff --git a/docs/connections.md b/docs/connections.md index c77239df486..8850e176dd4 100644 --- a/docs/connections.md +++ b/docs/connections.md @@ -61,7 +61,7 @@ setTimeout(function() { }, 60000); ``` -To disable buffering, turn off the [`bufferCommands` option on your schema](./guide.html#bufferCommands). +To disable buffering, turn off the [`bufferCommands` option on your schema](guide.html#bufferCommands). If you have `bufferCommands` on and your connection is hanging, try turning `bufferCommands` off to see if you haven't opened a connection properly. You can also disable `bufferCommands` globally: @@ -199,7 +199,7 @@ See [this page](http://mongodb.github.io/node-mongodb-native/3.1/reference/faq/)

Callback

The `connect()` function also accepts a callback parameter and returns a -[promise](./promises.html). +[promise](promises.html). ```javascript mongoose.connect(uri, options, function(error) { @@ -396,8 +396,8 @@ The `mongoose.createConnection()` function takes the same arguments as const conn = mongoose.createConnection('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]', options); ``` -This [connection](./api.html#connection_Connection) object is then used to -create and retrieve [models](./api.html#model_Model). Models are +This [connection](api.html#connection_Connection) object is then used to +create and retrieve [models](api.html#model_Model). Models are **always** scoped to a single connection. ```javascript @@ -526,4 +526,4 @@ mongoose.connect(myUri, {

Next Up

-Now that we've covered connections, let's take a look at [models](/docs/models.html). \ No newline at end of file +Now that we've covered connections, let's take a look at [models](/docs/models.html). diff --git a/docs/documents.md b/docs/documents.md index 5c762adc7f9..71c17b502d2 100644 --- a/docs/documents.md +++ b/docs/documents.md @@ -1,8 +1,8 @@ ## Documents -Mongoose [documents](./api/document.html) represent a one-to-one mapping +Mongoose [documents](api/document.html) represent a one-to-one mapping to documents as stored in MongoDB. Each document is an instance of its -[Model](./models.html). +[Model](models.html).
  • Documents vs Models
  • @@ -134,7 +134,7 @@ await Person.updateOne({}, { age: 'bar' }); await Person.updateOne({}, { age: -1 }, { runValidators: true }); ``` -Read the [validation](./validation.html) guide for more details. +Read the [validation](validation.html) guide for more details.

    Overwriting

    @@ -161,4 +161,4 @@ await Person.replaceOne({ _id }, { name: 'Jean-Luc Picard' }); ### Next Up Now that we've covered Documents, let's take a look at -[Subdocuments](/docs/subdocs.html). \ No newline at end of file +[Subdocuments](/docs/subdocs.html). diff --git a/docs/faq.md b/docs/faq.md index 33cc25e3f2e..a7a3521858e 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -25,7 +25,7 @@ doc.save(); **A**. Mongoose doesn't create getters/setters for array indexes; without them mongoose never gets notified of the change and so doesn't know to persist the new value. There are two workarounds: -[`MongooseArray#set`](./api.html#types_array_MongooseArray.set) or +[`MongooseArray#set`](api.html#types_array_MongooseArray.set) or [`Document#markModified()`](/docs/api/document.html#document_Document-markModified). ```javascript @@ -123,7 +123,7 @@ console.log(new Model()); **A**. This is a performance optimization. These empty objects are not saved to the database, nor are they in the result `toObject()`, nor do they show -up in `JSON.stringify()` output unless you turn off the [`minimize` option](./guide.html#minimize). +up in `JSON.stringify()` output unless you turn off the [`minimize` option](guide.html#minimize). The reason for this behavior is that Mongoose's change detection and getters/setters are based on [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). @@ -132,7 +132,7 @@ the overhead of running `Object.defineProperty()` every time a document is creat mongoose defines properties on the `Model` prototype when the model is compiled. Because mongoose needs to define getters and setters for `nested.prop`, `nested` must always be defined as an object on a mongoose document, even if `nested` -is undefined on the underlying [POJO](./guide.html#minimize). +is undefined on the underlying [POJO](guide.html#minimize).
    @@ -161,7 +161,7 @@ foo(); // "undefined"
    -**Q**. I'm using an arrow function for a [virtual](./guide.html#virtuals), [middleware](./middleware.html), [getter](./api.html#schematype_SchemaType-get)/[setter](./api.html#schematype_SchemaType-set), or [method](./guide.html#methods) and the value of `this` is wrong. +**Q**. I'm using an arrow function for a [virtual](guide.html#virtuals), [middleware](middleware.html), [getter](api.html#schematype_SchemaType-get)/[setter](api.html#schematype_SchemaType-set), or [method](guide.html#methods) and the value of `this` is wrong. **A**. Arrow functions [handle the `this` keyword much differently than conventional functions](https://masteringjs.io/tutorials/fundamentals/arrow#why-not-arrow-functions). Mongoose getters/setters depend on `this` to give you access to the document that you're writing to, but this functionality does not work with arrow functions. Do **not** use arrow functions for mongoose getters/setters unless do not intend to access the document in the getter/setter. @@ -254,7 +254,7 @@ new Schema({ **Q**. All function calls on my models hang, what am I doing wrong? **A**. By default, mongoose will buffer your function calls until it can -connect to MongoDB. Read the [buffering section of the connection docs](./connections.html#buffering) +connect to MongoDB. Read the [buffering section of the connection docs](connections.html#buffering) for more information.
    @@ -274,7 +274,7 @@ mongoose.set('debug', { color: false }) mongoose.set('debug', { shell: true }) ``` -For more debugging options (streams, callbacks), see the ['debug' option under `.set()`](./api.html#mongoose_Mongoose-set). +For more debugging options (streams, callbacks), see the ['debug' option under `.set()`](api.html#mongoose_Mongoose-set).
    @@ -458,4 +458,4 @@ await BlogPost.updateOne({ title: 'Introduction to Promises' }, update, (err, re **Something to add?** -If you'd like to contribute to this page, please [visit it](https://github.com/Automattic/mongoose/tree/master/docs/faq.md) on github and use the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button to send a pull request. \ No newline at end of file +If you'd like to contribute to this page, please [visit it](https://github.com/Automattic/mongoose/tree/master/docs/faq.md) on github and use the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button to send a pull request. diff --git a/docs/guide.md b/docs/guide.md index acf75a90487..a01f153d2b3 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -1,6 +1,6 @@ ## Schemas -If you haven't yet done so, please take a minute to read the [quickstart](./index.html) to get an idea of how Mongoose works. +If you haven't yet done so, please take a minute to read the [quickstart](index.html) to get an idea of how Mongoose works. If you are migrating from 4.x to 5.x please take a moment to read the [migration guide](/docs/migrating_to_5.html).
      @@ -43,12 +43,12 @@ collection and defines the shape of the documents within that collection. ``` If you want to add additional keys later, use the -[Schema#add](./api.html#schema_Schema-add) method. +[Schema#add](api.html#schema_Schema-add) method. Each key in our code `blogSchema` defines a property in our documents which -will be cast to its associated [SchemaType](./api.html#schematype_SchemaType). +will be cast to its associated [SchemaType](api.html#schematype_SchemaType). For example, we've defined a property `title` which will be cast to the -[String](./api.html#schema-string-js) SchemaType and property `date` +[String](api.html#schema-string-js) SchemaType and property `date` which will be cast to a `Date` SchemaType. Notice above that if a property only requires a type, it can be specified using @@ -63,34 +63,34 @@ In these cases, Mongoose only creates actual schema paths for leaves in the tree. (like `meta.votes` and `meta.favs` above), and the branches do not have actual paths. A side-effect of this is that `meta` 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](./subdocs.html) section -for more information on how to do this. Also read the [Mixed](./schematypes.html) +needs to be created up the tree - see the [Subdocuments](subdocs.html) section +for more information on how to do this. Also read the [Mixed](schematypes.html) subsection of the SchemaTypes guide for some gotchas. The permitted SchemaTypes are: -* [String](./schematypes.html#strings) -* [Number](./schematypes.html#numbers) -* [Date](./schematypes.html#dates) -* [Buffer](./schematypes.html#buffers) -* [Boolean](./schematypes.html#booleans) -* [Mixed](./schematypes.html#mixed) -* [ObjectId](./schematypes.html#objectids) -* [Array](./schematypes.html#arrays) -* [Decimal128](./api.html#mongoose_Mongoose-Decimal128) -* [Map](./schematypes.html#maps) +* [String](schematypes.html#strings) +* [Number](schematypes.html#numbers) +* [Date](schematypes.html#dates) +* [Buffer](schematypes.html#buffers) +* [Boolean](schematypes.html#booleans) +* [Mixed](schematypes.html#mixed) +* [ObjectId](schematypes.html#objectids) +* [Array](schematypes.html#arrays) +* [Decimal128](api.html#mongoose_Mongoose-Decimal128) +* [Map](schematypes.html#maps) -Read more about [SchemaTypes here](./schematypes.html). +Read more about [SchemaTypes here](schematypes.html). Schemas not only define the structure of your document and casting of properties, they also define document [instance methods](#methods), [static Model methods](#statics), [compound indexes](#indexes), -and document lifecycle hooks called [middleware](./middleware.html). +and document lifecycle hooks called [middleware](middleware.html).

      Creating a model

      To use our schema definition, we need to convert our `blogSchema` into a -[Model](./models.html) we can work with. +[Model](models.html) we can work with. To do so, we pass it into `mongoose.model(modelName, schema)`: ```javascript @@ -137,8 +137,8 @@ await doc.save(); // works

      Instance methods

      -Instances of `Models` are [documents](./documents.html). Documents have -many of their own [built-in instance methods](./api/document.html). +Instances of `Models` are [documents](documents.html). Documents have +many of their own [built-in instance methods](api/document.html). We may also define our own custom document instance methods. ```javascript @@ -163,8 +163,8 @@ to them. }); ``` -* Overwriting a default mongoose document method may lead to unpredictable results. See [this](./api.html#schema_Schema.reserved) for more details. -* The example above uses the `Schema.methods` object directly to save an instance method. You can also use the `Schema.method()` helper as described [here](./api.html#schema_Schema-method). +* Overwriting a default mongoose document method may lead to unpredictable results. See [this](api.html#schema_Schema.reserved) for more details. +* The example above uses the `Schema.methods` object directly to save an instance method. You can also use the `Schema.method()` helper as described [here](api.html#schema_Schema-method). * Do **not** declare methods using ES6 arrow functions (`=>`). Arrow functions [explicitly prevent binding `this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this), so your method will **not** have access to the document and the above examples will not work.

      Statics

      @@ -194,7 +194,7 @@ Do **not** declare statics using ES6 arrow functions (`=>`). Arrow functions [ex 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](./queries.html). +[chainable query builder API](queries.html). ```javascript animalSchema.query.byName = function(name) { @@ -215,7 +215,7 @@ but for mongoose queries. Query helper methods let you extend mongoose's

      Indexes

      MongoDB supports [secondary indexes](http://docs.mongodb.org/manual/indexes/). -With mongoose, we define these indexes within our `Schema` [at](./api.html#schematype_SchemaType-index) [the](./api.html#schematype_SchemaType-unique) [path](./api.html#schematype_SchemaType-sparse) [level](./api.html#schema_date_SchemaDate-expires) or the `schema` level. +With mongoose, we define these indexes within our `Schema` [at](api.html#schematype_SchemaType-index) [the](api.html#schematype_SchemaType-unique) [path](api.html#schematype_SchemaType-sparse) [level](api.html#schema_date_SchemaDate-expires) or the `schema` level. Defining indexes at the schema level is necessary when creating [compound indexes](https://docs.mongodb.com/manual/core/index-compound/). @@ -259,11 +259,11 @@ building or an error occurred. }); ``` -See also the [Model#ensureIndexes](./api.html#model_Model.ensureIndexes) method. +See also the [Model#ensureIndexes](api.html#model_Model.ensureIndexes) method.

      Virtuals

      -[Virtuals](./api.html#schema_Schema-virtual) are document properties that +[Virtuals](api.html#schema_Schema-virtual) 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. @@ -296,7 +296,7 @@ But [concatenating](https://masteringjs.io/tutorials/fundamentals/string-concat) last name every time can get cumbersome. And what if you want to do some extra processing on the name, like [removing diacritics](https://www.npmjs.com/package/diacritics)? A -[virtual property getter](./api.html#virtualtype_VirtualType-get) lets you +[virtual property getter](api.html#virtualtype_VirtualType-get) lets you define a `fullName` property that won't get persisted to MongoDB. ```javascript @@ -316,7 +316,7 @@ If you use `toJSON()` or `toObject()` mongoose will *not* include virtuals by default. This includes the output of calling [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) on a Mongoose document, because [`JSON.stringify()` calls `toJSON()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description). Pass `{ virtuals: true }` to either -[`toObject()`](./api.html#document_Document-toObject) or [`toJSON()`](./api.html#document_Document-toJSON). +[`toObject()`](api.html#document_Document-toObject) or [`toJSON()`](api.html#document_Document-toJSON). You can also add a custom setter to your virtual that will let you set both first name and last name via the `fullName` virtual. @@ -518,7 +518,7 @@ new Schema({..}, { capped: { size: 1024, max: 1000, autoIndexId: true } });

      option: collection

      Mongoose by default produces a collection name by passing the model name to -the [utils.toCollectionName](./api.html#utils_exports.toCollectionName) method. +the [utils.toCollectionName](api.html#utils_exports.toCollectionName) method. This method pluralizes the name. Set this option if you need a different name for your collection. @@ -1061,7 +1061,7 @@ thing.save(); // version is not incremented

      option: timestamps

      The `timestamps` option tells mongoose to assign `createdAt` and `updatedAt` fields -to your schema. The type assigned is [Date](./api.html#schema-date-js). +to your schema. The type assigned is [Date](api.html#schema-date-js). By default, the names of the fields are `createdAt` and `updatedAt`. Customize the field names by setting `timestamps.createdAt` and `timestamps.updatedAt`. @@ -1255,7 +1255,7 @@ console.log(schema.virtuals); // { myVirtual: VirtualType { ... } }

      Pluggable

      -Schemas are also [pluggable](./plugins.html) which allows us to package up reusable features into +Schemas are also [pluggable](plugins.html) which allows us to package up reusable features into plugins that can be shared with the community or just between your projects.

      Further Reading

      diff --git a/docs/middleware.md b/docs/middleware.md index be5bcec8075..c5b2d5bbb76 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -2,7 +2,7 @@ Middleware (also called pre and post *hooks*) are functions which are passed control during execution of asynchronous functions. Middleware is specified -on the schema level and is useful for writing [plugins](./plugins.html). +on the schema level and is useful for writing [plugins](plugins.html).
      • Types of Middleware
      • @@ -36,37 +36,37 @@ In document middleware functions, `this` refers to the document. Query middleware is supported for the following Model and Query functions. In query middleware functions, `this` refers to the query. -* [count](./api.html#query_Query-count) -* [deleteMany](./api.html#query_Query-deleteMany) -* [deleteOne](./api.html#query_Query-deleteOne) -* [find](./api.html#query_Query-find) -* [findOne](./api.html#query_Query-findOne) -* [findOneAndDelete](./api.html#query_Query-findOneAndDelete) -* [findOneAndRemove](./api.html#query_Query-findOneAndRemove) -* [findOneAndUpdate](./api.html#query_Query-findOneAndUpdate) -* [remove](./api.html#model_Model.remove) -* [update](./api.html#query_Query-update) -* [updateOne](./api.html#query_Query-updateOne) -* [updateMany](./api.html#query_Query-updateMany) +* [count](api.html#query_Query-count) +* [deleteMany](api.html#query_Query-deleteMany) +* [deleteOne](api.html#query_Query-deleteOne) +* [find](api.html#query_Query-find) +* [findOne](api.html#query_Query-findOne) +* [findOneAndDelete](api.html#query_Query-findOneAndDelete) +* [findOneAndRemove](api.html#query_Query-findOneAndRemove) +* [findOneAndUpdate](api.html#query_Query-findOneAndUpdate) +* [remove](api.html#model_Model.remove) +* [update](api.html#query_Query-update) +* [updateOne](api.html#query_Query-updateOne) +* [updateMany](api.html#query_Query-updateMany) Aggregate middleware is for `MyModel.aggregate()`. Aggregate middleware executes when you call `exec()` on an aggregate object. -In aggregate middleware, `this` refers to the [aggregation object](./api.html#model_Model.aggregate). +In aggregate middleware, `this` refers to the [aggregation object](api.html#model_Model.aggregate). -* [aggregate](./api.html#model_Model.aggregate) +* [aggregate](api.html#model_Model.aggregate) Model middleware is supported for the following model functions. In model middleware functions, `this` refers to the model. -* [insertMany](./api.html#model_Model.insertMany) +* [insertMany](api.html#model_Model.insertMany) All middleware types support pre and post hooks. How pre and post hooks work is described in more detail below. **Note:** If you specify `schema.pre('remove')`, Mongoose will register this -middleware for [`doc.remove()`](./api.html#model_Model-remove) by default. If you -want to your middleware to run on [`Query.remove()`](./api.html#query_Query-remove) -use [`schema.pre('remove', { query: true, document: false }, fn)`](./api.html#schema_Schema-pre). +middleware for [`doc.remove()`](api.html#model_Model-remove) by default. If you +want to your middleware to run on [`Query.remove()`](api.html#query_Query-remove) +use [`schema.pre('remove', { query: true, document: false }, fn)`](api.html#schema_Schema-pre). **Note:** Unlike `schema.pre('remove')`, Mongoose registers `updateOne` and `deleteOne` middleware on `Query#updateOne()` and `Query#deleteOne()` by default. @@ -75,7 +75,7 @@ This means that both `doc.updateOne()` and `Model.updateOne()` trigger `updateOne` or `deleteOne` middleware as document middleware, use `schema.pre('updateOne', { document: true, query: false })`. -**Note:** The [`create()`](./api.html#model_Model.create) function fires `save()` hooks. +**Note:** The [`create()`](api.html#model_Model.create) function fires `save()` hooks.

        Pre

        @@ -482,7 +482,7 @@ pipeline from middleware. Certain Mongoose hooks are synchronous, which means they do **not** support functions that return promises or receive a `next()` callback. Currently, -only `init` hooks are synchronous, because the [`init()` function](./api.html#document_Document-init) +only `init` hooks are synchronous, because the [`init()` function](api.html#document_Document-init) is synchronous. Below is an example of using pre and post init hooks. ```javascript diff --git a/docs/models.md b/docs/models.md index 257ea18bdce..a758667b50b 100644 --- a/docs/models.md +++ b/docs/models.md @@ -1,8 +1,8 @@ ## Models -[Models](./api.html#model-js) are fancy constructors compiled from +[Models](api.html#model-js) are fancy constructors compiled from `Schema` definitions. An instance of a model is called a -[document](./documents.html). Models are responsible for creating and +[document](documents.html). Models are responsible for creating and reading documents from the underlying MongoDB database. * [Compiling your first model](#compiling) @@ -33,7 +33,7 @@ before calling `.model()`! ### Constructing Documents -An instance of a model is called a [document](./documents.html). Creating +An instance of a model is called a [document](documents.html). Creating them and saving to the database is easy. ```javascript @@ -75,13 +75,13 @@ const Tank = connection.model('Tank', yourSchema); ### Querying -Finding documents is easy with Mongoose, which supports the [rich](http://www.mongodb.org/display/DOCS/Advanced+Queries) query syntax of MongoDB. Documents can be retreived using each `models` [find](./api.html#model_Model.find), [findById](./api.html#model_Model.findById), [findOne](./api.html#model_Model.findOne), or [where](./api.html#model_Model.where) static methods. +Finding documents is easy with Mongoose, which supports the [rich](http://www.mongodb.org/display/DOCS/Advanced+Queries) query syntax of MongoDB. Documents can be retreived using each `models` [find](api.html#model_Model.find), [findById](api.html#model_Model.findById), [findOne](api.html#model_Model.findOne), or [where](api.html#model_Model.where) static methods. ```javascript Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(callback); ``` -See the chapter on [queries](./queries.html) for more details on how to use the [Query](./api.html#query-js) api. +See the chapter on [queries](queries.html) for more details on how to use the [Query](api.html#query-js) api. ### Deleting @@ -99,7 +99,7 @@ Tank.deleteOne({ size: 'large' }, function (err) { Each `model` has its own `update` method for modifying documents in the database without returning them to your application. See the -[API](./api.html#model_Model.updateOne) docs for more detail. +[API](api.html#model_Model.updateOne) docs for more detail. ```javascript Tank.updateOne({ size: 'large' }, { name: 'T-90' }, function(err, res) { @@ -109,7 +109,7 @@ Tank.updateOne({ size: 'large' }, { name: 'T-90' }, function(err, res) { ``` _If you want to update a single document in the db and return it to your -application, use [findOneAndUpdate](./api.html#model_Model.findOneAndUpdate) +application, use [findOneAndUpdate](api.html#model_Model.findOneAndUpdate) instead._ ### Change Streams @@ -156,8 +156,8 @@ You can read more about [change streams in mongoose in this blog post](http://th ### Yet more -The [API docs](./api.html#model_Model) cover many additional methods available like [count](./api.html#model_Model.count), [mapReduce](./api.html#model_Model.mapReduce), [aggregate](./api.html#model_Model.aggregate), and [more](./api.html#model_Model.findOneAndRemove). +The [API docs](api.html#model_Model) cover many additional methods available like [count](api.html#model_Model.count), [mapReduce](api.html#model_Model.mapReduce), [aggregate](api.html#model_Model.aggregate), and [more](api.html#model_Model.findOneAndRemove). ### Next Up -Now that we've covered `Models`, let's take a look at [Documents](/docs/documents.html). \ No newline at end of file +Now that we've covered `Models`, let's take a look at [Documents](/docs/documents.html). diff --git a/docs/populate.md b/docs/populate.md index c7c8bdbd8c5..a2ddbece18b 100644 --- a/docs/populate.md +++ b/docs/populate.md @@ -25,7 +25,7 @@ const Story = mongoose.model('Story', storySchema); const Person = mongoose.model('Person', personSchema); ``` -So far we've created two [Models](./models.html). Our `Person` model has +So far we've created two [Models](models.html). Our `Person` model has its `stories` field set to an array of `ObjectId`s. The `ref` option is what tells Mongoose which model to use during population, in our case the `Story` model. All `_id`s we store here must be document `_id`s from @@ -105,7 +105,7 @@ is replaced with the mongoose document returned from the database by performing a separate query before returning the results. Arrays of refs work the same way. Just call the -[populate](./api.html#query_Query-populate) method on the query and an +[populate](api.html#query_Query-populate) method on the query and an array of documents will be returned _in place_ of the original `_id`s.

        Setting Populated Fields

        @@ -184,7 +184,7 @@ story.authors; // `[]` What if we only want a few specific fields returned for the populated documents? This can be accomplished by passing the usual -[field name syntax](./api.html#query_Query-select) as the second argument +[field name syntax](api.html#query_Query-select) as the second argument to the populate method: ```javascript @@ -367,10 +367,10 @@ Story. ``` The documents returned from -[query population](./api.html#query_Query-populate) become fully +[query population](api.html#query_Query-populate) become fully functional, `remove`able, `save`able documents unless the -[lean](./api.html#query_Query-lean) option is specified. Do not confuse -them with [sub docs](./subdocs.html). Take caution when calling its +[lean](api.html#query_Query-lean) option is specified. Do not confuse +them with [sub docs](subdocs.html). Take caution when calling its remove method because you'll be removing it from the database, not just the array. @@ -378,7 +378,7 @@ the array. If you have an existing mongoose document and want to populate some of its paths, you can use the -[Document#populate()](./api.html#document_Document-populate) method. +[Document#populate()](api.html#document_Document-populate) method. Just make sure you call [`Document#execPopulate()`](/docs/api/document.html#document_Document-execPopulate) to execute the `populate()`. @@ -406,8 +406,8 @@ person.populated('fans'); // Array of ObjectIds

        Populating multiple existing documents

        If we have one or many mongoose documents or even plain objects -(_like [mapReduce](./api.html#model_Model.mapReduce) output_), we may -populate them using the [Model.populate()](./api.html#model_Model.populate) +(_like [mapReduce](api.html#model_Model.mapReduce) output_), we may +populate them using the [Model.populate()](api.html#model_Model.populate) method. This is what `Document#populate()` and `Query#populate()` use to populate documents. diff --git a/docs/queries.md b/docs/queries.md index f1ee795559c..ad2fa651ed1 100644 --- a/docs/queries.md +++ b/docs/queries.md @@ -1,6 +1,6 @@ ## Queries -Mongoose [models](./models.html) provide several static helper functions +Mongoose [models](models.html) provide several static helper functions for [CRUD operations](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete). Each of these functions returns a [mongoose `Query` object](http://mongoosejs.com/docs/api.html#Query). @@ -55,7 +55,7 @@ Mongoose executed the query and passed the results to `callback`. All callbacks `callback(error, result)`. If an error occurs executing the query, the `error` parameter will contain an error document, and `result` will be null. If the query is successful, the `error` parameter will be null, and the `result` will be populated with the results of the query. -Anywhere a callback is passed to a query in Mongoose, the callback follows the pattern `callback(error, results)`. What `results` is depends on the operation: For `findOne()` it is a [potentially-null single document](./api.html#model_Model.findOne), `find()` a [list of documents](./api.html#model_Model.find), `count()` [the number of documents](./api.html#model_Model.count), `update()` the [number of documents affected](./api.html#model_Model.update), etc. The [API docs for Models](./api.html#model-js) provide more detail on what is passed to the callbacks. +Anywhere a callback is passed to a query in Mongoose, the callback follows the pattern `callback(error, results)`. What `results` is depends on the operation: For `findOne()` it is a [potentially-null single document](api.html#model_Model.findOne), `find()` a [list of documents](api.html#model_Model.find), `count()` [the number of documents](api.html#model_Model.count), `update()` the [number of documents affected](api.html#model_Model.update), etc. The [API docs for Models](api.html#model-js) provide more detail on what is passed to the callbacks. Now let's look at what happens when no `callback` is passed: @@ -75,7 +75,7 @@ query.exec(function (err, person) { }); ``` -In the above code, the `query` variable is of type [Query](./api.html#query-js). +In the above code, the `query` variable is of type [Query](api.html#query-js). A `Query` enables you to build up a query using chaining syntax, rather than specifying a JSON object. The below 2 examples are equivalent. @@ -105,7 +105,7 @@ Person. exec(callback); ``` -A full list of [Query helper functions can be found in the API docs](./api.html#query-js). +A full list of [Query helper functions can be found in the API docs](api.html#query-js).

        @@ -156,16 +156,16 @@ await BlogPost.updateOne({ title: 'Introduction to Promises' }, update, (err, re

        References to other documents

        There are no joins in MongoDB but sometimes we still want references to -documents in other collections. This is where [population](./populate.html) +documents in other collections. This is where [population](populate.html) comes in. Read more about how to include documents from other collections in -your query results [here](./api.html#query_Query-populate). +your query results [here](api.html#query_Query-populate).

        Streaming

        You can [stream](http://nodejs.org/api/stream.html) query results from MongoDB. You need to call the -[Query#cursor()](./api.html#query_Query-cursor) function to return an instance of -[QueryCursor](./api.html#query_Query-cursor). +[Query#cursor()](api.html#query_Query-cursor) function to return an instance of +[QueryCursor](api.html#query_Query-cursor). ```javascript const cursor = Person.find({ occupation: /host/ }).cursor(); diff --git a/docs/schematypes.md b/docs/schematypes.md index bcc2cc5a9ce..51552bdb52c 100644 --- a/docs/schematypes.md +++ b/docs/schematypes.md @@ -1,12 +1,12 @@

        SchemaTypes

        SchemaTypes handle definition of path -[defaults](./api.html#schematype_SchemaType-default), -[validation](./api.html#schematype_SchemaType-validate), +[defaults](api.html#schematype_SchemaType-default), +[validation](api.html#schematype_SchemaType-validate), [getters](#getters), -[setters](./api.html#schematype_SchemaType-set), -[field selection defaults](./api.html#schematype_SchemaType-select) for -[queries](./api.html#query-js), +[setters](api.html#schematype_SchemaType-set), +[field selection defaults](api.html#schematype_SchemaType-select) for +[queries](api.html#query-js), and other general characteristics for Mongoose document properties.
          @@ -57,7 +57,7 @@ Check out [Mongoose's plugins search](http://plugins.mongoosejs.io) to find plug - [Mixed](#mixed) - [ObjectId](#objectids) - [Array](#arrays) -- [Decimal128](./api.html#mongoose_Mongoose-Decimal128) +- [Decimal128](api.html#mongoose_Mongoose-Decimal128) - [Map](#maps) - [Schema](#schemas) @@ -208,13 +208,13 @@ types.
          All Schema Types
          -* `required`: boolean or function, if true adds a [required validator](./validation.html#built-in-validators) for this property +* `required`: boolean or function, if true adds a [required validator](validation.html#built-in-validators) for this property * `default`: Any or function, sets a default value for the path. If the value is a function, the return value of the function is used as the default. * `select`: boolean, specifies default [projections](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/) for queries -* `validate`: function, adds a [validator function](./validation.html#built-in-validators) for this property +* `validate`: function, adds a [validator function](validation.html#built-in-validators) for this property * `get`: function, defines a custom getter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). * `set`: function, defines a custom setter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). -* `alias`: string, mongoose >= 4.10.0 only. Defines a [virtual](./guide.html#virtuals) with the given name that gets/sets this path. +* `alias`: string, mongoose >= 4.10.0 only. Defines a [virtual](guide.html#virtuals) with the given name that gets/sets this path. * `immutable`: boolean, defines path as immutable. Mongoose prevents you from changing immutable paths unless the parent document has `isNew: true`. * `transform`: function, Mongoose calls this function when you call [`Document#toJSON()`](/docs/api/document.html#document_Document-toJSON) function, including when you [`JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript) a document. @@ -264,17 +264,17 @@ const schema2 = new Schema({ * `lowercase`: boolean, whether to always call `.toLowerCase()` on the value * `uppercase`: boolean, whether to always call `.toUpperCase()` on the value * `trim`: boolean, whether to always call `.trim()` on the value -* `match`: RegExp, creates a [validator](./validation.html) that checks if the value matches the given regular expression -* `enum`: Array, creates a [validator](./validation.html) that checks if the value is in the given array. -* `minLength`: Number, creates a [validator](./validation.html) that checks if the value length is not less than the given number -* `maxLength`: Number, creates a [validator](./validation.html) that checks if the value length is not greater than the given number +* `match`: RegExp, creates a [validator](validation.html) that checks if the value matches the given regular expression +* `enum`: Array, creates a [validator](validation.html) that checks if the value is in the given array. +* `minLength`: Number, creates a [validator](validation.html) that checks if the value length is not less than the given number +* `maxLength`: Number, creates a [validator](validation.html) that checks if the value length is not greater than the given number * `populate`: Object, sets default [populate options](/docs/populate.html#query-conditions)
          Number
          -* `min`: Number, creates a [validator](./validation.html) that checks if the value is greater than or equal to the given minimum. -* `max`: Number, creates a [validator](./validation.html) that checks if the value is less than or equal to the given maximum. -* `enum`: Array, creates a [validator](./validation.html) that checks if the value is strictly equal to one of the values in the given array. +* `min`: Number, creates a [validator](validation.html) that checks if the value is greater than or equal to the given minimum. +* `max`: Number, creates a [validator](validation.html) that checks if the value is less than or equal to the given maximum. +* `enum`: Array, creates a [validator](validation.html) that checks if the value is strictly equal to one of the values in the given array. * `populate`: Object, sets default [populate options](/docs/populate.html#query-conditions)
          Date
          @@ -408,7 +408,7 @@ like, but Mongoose loses the ability to auto detect and save those changes. To tell Mongoose that the value of a Mixed type has changed, you need to call `doc.markModified(path)`, passing the path to the Mixed type you just changed. -To avoid these side-effects, a [Subdocument](./subdocs.html) path may be used +To avoid these side-effects, a [Subdocument](subdocs.html) path may be used instead. ```javascript @@ -480,8 +480,8 @@ console.log(new M({ b: 'nay' }).b); // false

          Arrays

          -Mongoose supports arrays of [SchemaTypes](./api.html#schema_Schema.Types) -and arrays of [subdocuments](./subdocs.html). Arrays of SchemaTypes are +Mongoose supports arrays of [SchemaTypes](api.html#schema_Schema.Types) +and arrays of [subdocuments](subdocs.html). Arrays of SchemaTypes are also called _primitive arrays_, and arrays of subdocuments are also called _document arrays_. @@ -676,7 +676,7 @@ schema.path('arr.0.url').get(v => `${root}${v}`);

          Schemas

          -To declare a path as another [schema](./guide.html#definition), +To declare a path as another [schema](guide.html#definition), set `type` to the sub-schema's instance. To set a default value based on the sub-schema's shape, simply set a default value, diff --git a/docs/subdocs.md b/docs/subdocs.md index 1b3d778c968..4f34f7daa75 100644 --- a/docs/subdocs.md +++ b/docs/subdocs.md @@ -36,7 +36,7 @@ a group of fields (e.g. dateRange.fromDate <= dateRange.toDate). ### What is a Subdocument? Subdocuments are similar to normal documents. Nested schemas can have -[middleware](./middleware.html), [custom validation logic](./validation.html), +[middleware](middleware.html), [custom validation logic](validation.html), virtuals, and any other feature top-level schemas can use. The major difference is that subdocuments are not saved individually, they are saved whenever their top-level parent @@ -53,7 +53,7 @@ parent.children[0].name = 'Matthew'; parent.save(callback); ``` -Subdocuments have `save` and `validate` [middleware](./middleware.html) +Subdocuments have `save` and `validate` [middleware](middleware.html) just like top-level documents. Calling `save()` on the parent document triggers the `save()` middleware for all its subdocuments, and the same for `validate()` middleware. @@ -222,7 +222,7 @@ doc.child; // { age: 0 } ### Finding a Subdocument Each subdocument has an `_id` by default. Mongoose document arrays have a -special [id](./api.html#types_documentarray_MongooseDocumentArray-id) method +special [id](api.html#types_documentarray_MongooseDocumentArray-id) method for searching a document array to find a document with a given `_id`. ```javascript const doc = parent.children.id(_id); @@ -231,9 +231,9 @@ const doc = parent.children.id(_id); ### Adding Subdocs to Arrays MongooseArray methods such as -[push](./api.html#mongoosearray_MongooseArray-push), -[unshift](./api.html#mongoosearray_MongooseArray-unshift), -[addToSet](./api.html#mongoosearray_MongooseArray-addToSet), +[push](api.html#mongoosearray_MongooseArray-push), +[unshift](api.html#mongoosearray_MongooseArray-unshift), +[addToSet](api.html#mongoosearray_MongooseArray-addToSet), and others cast arguments to their proper types transparently: ```javascript const Parent = mongoose.model('Parent'); @@ -252,7 +252,7 @@ parent.save(function (err) { ``` Subdocs may also be created without adding them to the array by using the -[create](./api.html#types_documentarray_MongooseDocumentArray.create) +[create](api.html#types_documentarray_MongooseDocumentArray.create) method of MongooseArrays. ```javascript @@ -262,7 +262,7 @@ const newdoc = parent.children.create({ name: 'Aaron' }); ### Removing Subdocs Each subdocument has it's own -[remove](./api.html#types_embedded_EmbeddedDocument-remove) method. For +[remove](api.html#types_embedded_EmbeddedDocument-remove) method. For an array subdocument, this is equivalent to calling `.pull()` on the subdocument. For a single nested subdocument, `remove()` is equivalent to setting the subdocument to `null`. @@ -389,4 +389,4 @@ const schema = new Schema({ ### Next Up Now that we've covered Subdocuments, let's take a look at -[querying](./queries.html). +[querying](queries.html). diff --git a/docs/validation.md b/docs/validation.md index 56cc4071f20..c2dbffd1413 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -2,13 +2,13 @@ Before we get into the specifics of validation syntax, please keep the following rules in mind: -- Validation is defined in the [SchemaType](./schematypes.html) -- Validation is [middleware](./middleware.html). Mongoose registers validation as a `pre('save')` hook on every schema by default. -- You can disable automatic validation before save by setting the [validateBeforeSave](./guide.html#validateBeforeSave) option +- Validation is defined in the [SchemaType](schematypes.html) +- Validation is [middleware](middleware.html). Mongoose registers validation as a `pre('save')` hook on every schema by default. +- You can disable automatic validation before save by setting the [validateBeforeSave](guide.html#validateBeforeSave) option - You can manually run validation using `doc.validate(callback)` or `doc.validateSync()` -- You can manually mark a field as invalid (causing validation to fail) by using [`doc.invalidate(...)`](./api.html#document_Document-invalidate) -- Validators are not run on undefined values. The only exception is the [`required` validator](./api.html#schematype_SchemaType-required). -- Validation is asynchronously recursive; when you call [Model#save](./api.html#model_Model-save), sub-document validation is executed as well. If an error occurs, your [Model#save](./api.html#model_Model-save) callback receives it +- You can manually mark a field as invalid (causing validation to fail) by using [`doc.invalidate(...)`](api.html#document_Document-invalidate) +- Validators are not run on undefined values. The only exception is the [`required` validator](api.html#schematype_SchemaType-required). +- Validation is asynchronously recursive; when you call [Model#save](api.html#model_Model-save), sub-document validation is executed as well. If an error occurs, your [Model#save](api.html#model_Model-save) callback receives it - Validation is customizable ```javascript @@ -19,9 +19,9 @@ Before we get into the specifics of validation syntax, please keep the following Mongoose has several built-in validators. -- All [SchemaTypes](./schematypes.html) have the built-in [required](./api.html#schematype_SchemaType-required) validator. The required validator uses the [SchemaType's `checkRequired()` function](./api.html#schematype_SchemaType-checkRequired) to determine if the value satisfies the required validator. -- [Numbers](./api.html#schema-number-js) have [`min` and `max`](./schematypes.html#number-validators) validators. -- [Strings](./api.html#schema-string-js) have [`enum`, `match`, `minLength`, and `maxLength`](./schematypes.html#string-validators) validators. +- All [SchemaTypes](schematypes.html) have the built-in [required](api.html#schematype_SchemaType-required) validator. The required validator uses the [SchemaType's `checkRequired()` function](api.html#schematype_SchemaType-checkRequired) to determine if the value satisfies the required validator. +- [Numbers](api.html#schema-number-js) have [`min` and `max`](schematypes.html#number-validators) validators. +- [Strings](api.html#schema-string-js) have [`enum`, `match`, `minLength`, and `maxLength`](schematypes.html#string-validators) validators. Each of the validator links above provide more information about how to enable them and customize their error messages. @@ -61,7 +61,7 @@ to suit your needs. Custom validation is declared by passing a validation function. You can find detailed instructions on how to do this in the -[`SchemaType#validate()` API docs](./api.html#schematype_SchemaType-validate). +[`SchemaType#validate()` API docs](api.html#schematype_SchemaType-validate). ```javascript [require:Custom Validators] @@ -82,7 +82,7 @@ the value `false`, Mongoose will consider that a validation error. Errors returned after failed validation contain an `errors` object whose values are `ValidatorError` objects. Each -[ValidatorError](./api.html#error-validation-js) has `kind`, `path`, +[ValidatorError](api.html#error-validation-js) has `kind`, `path`, `value`, and `message` properties. A ValidatorError also may have a `reason` property. If an error was thrown in the validator, this property will contain the error that was @@ -192,4 +192,4 @@ of the array. ```javascript [require:Update Validators Only Run For Some Operations] -``` \ No newline at end of file +``` From 0cd01dad2fc7d923ff918d11376c46d52608b551 Mon Sep 17 00:00:00 2001 From: hasezoey Date: Mon, 14 Nov 2022 14:58:21 +0100 Subject: [PATCH 4/4] docs: change "/docs/" links to be relative re #12623 --- docs/connections.md | 16 ++++---- docs/deprecations.md | 44 ++++++++++----------- docs/documents.md | 6 +-- docs/faq.md | 6 +-- docs/geojson.md | 8 ++-- docs/guide.md | 42 ++++++++++---------- docs/guides.md | 61 +++++++++++++++--------------- docs/index.md | 10 ++--- docs/lambda.md | 2 +- docs/middleware.md | 34 ++++++++--------- docs/migrating_to_5.md | 4 +- docs/models.md | 2 +- docs/plugins.md | 8 ++-- docs/populate.md | 10 ++--- docs/promises.md | 2 +- docs/queries.md | 36 +++++++++--------- docs/schematypes.md | 16 ++++---- docs/subdocs.md | 4 +- docs/transactions.md | 16 ++++---- docs/tutorials/dates.md | 4 +- docs/tutorials/findoneandupdate.md | 6 +-- docs/tutorials/getters-setters.md | 6 +-- docs/tutorials/lean.md | 22 +++++------ docs/tutorials/ssl.md | 4 +- docs/tutorials/virtuals.md | 24 ++++++------ docs/typescript.md | 10 ++--- docs/typescript/schemas.md | 4 +- docs/typescript/statics.md | 4 +- docs/validation.md | 10 ++--- 29 files changed, 210 insertions(+), 211 deletions(-) diff --git a/docs/connections.md b/docs/connections.md index 8850e176dd4..0f03585fea9 100644 --- a/docs/connections.md +++ b/docs/connections.md @@ -71,11 +71,11 @@ mongoose.set('bufferCommands', false); ``` Note that buffering is also responsible for waiting until Mongoose -creates collections if you use the [`autoCreate` option](/docs/guide.html#autoCreate). +creates collections if you use the [`autoCreate` option](guide.html#autoCreate). If you disable buffering, you should also disable the `autoCreate` -option and use [`createCollection()`](/docs/api/model.html#model_Model.createCollection) -to create [capped collections](/docs/guide.html#capped) or -[collections with collations](/docs/guide.html#collation). +option and use [`createCollection()`](api/model.html#model_Model.createCollection) +to create [capped collections](guide.html#capped) or +[collections with collations](guide.html#collation). ```javascript const schema = new Schema({ @@ -149,7 +149,7 @@ Below are some of the options that are important for tuning Mongoose. * `useNewUrlParser` - The underlying MongoDB driver has deprecated their current [connection string](https://docs.mongodb.com/manual/reference/connection-string/) parser. Because this is a major change, they added the `useNewUrlParser` flag to allow users to fall back to the old parser if they find a bug in the new parser. You should set `useNewUrlParser: true` unless that prevents you from connecting. Note that if you specify `useNewUrlParser: true`, you **must** specify a port in your connection string, like `mongodb://localhost:27017/dbname`. The new url parser does _not_ support connection strings that do not have a port, like `mongodb://localhost/dbname`. * `useCreateIndex` - False by default. Set to `true` to make Mongoose's default index build use `createIndex()` instead of `ensureIndex()` to avoid deprecation warnings from the MongoDB driver. * `useFindAndModify` - True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. -* `useUnifiedTopology`- False by default. Set to `true` to opt in to using [the MongoDB driver's new connection management engine](/docs/deprecations.html#useunifiedtopology). You should set this option to `true`, except for the unlikely case that it prevents you from maintaining a stable connection. +* `useUnifiedTopology`- False by default. Set to `true` to opt in to using [the MongoDB driver's new connection management engine](deprecations.html#useunifiedtopology). You should set this option to `true`, except for the unlikely case that it prevents you from maintaining a stable connection. * `promiseLibrary` - Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). * `poolSize` - The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). * `socketTimeoutMS` - How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. @@ -157,7 +157,7 @@ Below are some of the options that are important for tuning Mongoose. * `authSource` - The database to use when authenticating with `user` and `pass`. In MongoDB, [users are scoped to a database](https://docs.mongodb.com/manual/tutorial/manage-users-and-roles/). If you are getting an unexpected login failure, you may need to set this option. The following options are important for tuning Mongoose only if you are -running **without** [the `useUnifiedTopology` option](/docs/deprecations.html#useunifiedtopology): +running **without** [the `useUnifiedTopology` option](deprecations.html#useunifiedtopology): * `autoReconnect` - The underlying MongoDB driver will automatically try to reconnect when it loses connection to MongoDB. Unless you are an extremely advanced user that wants to manage their own connection pool, do **not** set this option to `false`. * `reconnectTries` - If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. @@ -166,7 +166,7 @@ running **without** [the `useUnifiedTopology` option](/docs/deprecations.html#us * `connectTimeoutMS` - How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). The following options are important for tuning Mongoose only if you are -running **with** [the `useUnifiedTopology` option](/docs/deprecations.html#useunifiedtopology): +running **with** [the `useUnifiedTopology` option](deprecations.html#useunifiedtopology): * `serverSelectionTimeoutMS` - With `useUnifiedTopology`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds. If not set, the MongoDB driver defaults to using `30000` (30 seconds). * `heartbeatFrequencyMS` - With `useUnifiedTopology`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation. @@ -526,4 +526,4 @@ mongoose.connect(myUri, {

          Next Up

          -Now that we've covered connections, let's take a look at [models](/docs/models.html). +Now that we've covered connections, let's take a look at [models](models.html). diff --git a/docs/deprecations.md b/docs/deprecations.md index 628c304fca1..fe007b36139 100644 --- a/docs/deprecations.md +++ b/docs/deprecations.md @@ -32,15 +32,15 @@ removed in a future version. To use the new parser, pass option The MongoDB Node.js driver rewrote the tool it uses to parse [MongoDB connection strings](https://docs.mongodb.com/manual/reference/connection-string/). Because this is such a big change, they put the new connection string parser behind a flag. To turn on this option, pass the `useNewUrlParser` option to -[`mongoose.connect()`](/docs/api.html#mongoose_Mongoose-connect) -or [`mongoose.createConnection()`](/docs/api.html#mongoose_Mongoose-createConnection). +[`mongoose.connect()`](api.html#mongoose_Mongoose-connect) +or [`mongoose.createConnection()`](api.html#mongoose_Mongoose-createConnection). ```javascript mongoose.connect(uri, { useNewUrlParser: true }); mongoose.createConnection(uri, { useNewUrlParser: true }); ``` -You can also [set the global `useNewUrlParser` option](/docs/api.html#mongoose_Mongoose-set) +You can also [set the global `useNewUrlParser` option](api.html#mongoose_Mongoose-set) to turn on `useNewUrlParser` for every connection by default. ```javascript @@ -56,7 +56,7 @@ with `{ useNewUrlParser: true }`, please [open an issue on GitHub](https://githu

          findAndModify()

          -If you use [`Model.findOneAndUpdate()`](/docs/api.html#model_Model.findOneAndUpdate), +If you use [`Model.findOneAndUpdate()`](api.html#model_Model.findOneAndUpdate), by default you'll see one of the below deprecation warnings. ``` @@ -67,7 +67,7 @@ DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate Mongoose's `findOneAndUpdate()` long pre-dates the MongoDB driver's `findOneAndUpdate()` function, so it uses the MongoDB driver's [`findAndModify()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findAndModify) instead. You can opt in to using the MongoDB driver's `findOneAndUpdate()` -function using the [`useFindAndModify` global option](/docs/api.html#mongoose_Mongoose-set). +function using the [`useFindAndModify` global option](api.html#mongoose_Mongoose-set). ```javascript // Make Mongoose use `findOneAndUpdate()`. Note that this option is `true` @@ -86,15 +86,15 @@ no intentional backwards breaking changes, so you should be able to turn this option on without any code changes. If you discover any issues, please [open an issue on GitHub](https://github.com/Automattic/mongoose/issues/new). -* [`Model.findByIdAndDelete()`](/docs/api.html#model_Model.findByIdAndDelete) -* [`Model.findByIdAndRemove()`](/docs/api.html#model_Model.findByIdAndRemove) -* [`Model.findByIdAndUpdate()`](/docs/api.html#model_Model.findByIdAndUpdate) -* [`Model.findOneAndDelete()`](/docs/api.html#model_Model.findOneAndDelete) -* [`Model.findOneAndRemove()`](/docs/api.html#model_Model.findOneAndRemove) -* [`Model.findOneAndUpdate()`](/docs/api.html#model_Model.findOneAndUpdate) -* [`Query.findOneAndDelete()`](/docs/api.html#query_Query-findOneAndDelete) -* [`Query.findOneAndRemove()`](/docs/api.html#query_Query-findOneAndRemove) -* [`Query.findOneAndUpdate()`](/docs/api.html#query_Query-findOneAndUpdate) +* [`Model.findByIdAndDelete()`](api.html#model_Model.findByIdAndDelete) +* [`Model.findByIdAndRemove()`](api.html#model_Model.findByIdAndRemove) +* [`Model.findByIdAndUpdate()`](api.html#model_Model.findByIdAndUpdate) +* [`Model.findOneAndDelete()`](api.html#model_Model.findOneAndDelete) +* [`Model.findOneAndRemove()`](api.html#model_Model.findOneAndRemove) +* [`Model.findOneAndUpdate()`](api.html#model_Model.findOneAndUpdate) +* [`Query.findOneAndDelete()`](api.html#query_Query-findOneAndDelete) +* [`Query.findOneAndRemove()`](api.html#query_Query-findOneAndRemove) +* [`Query.findOneAndUpdate()`](api.html#query_Query-findOneAndUpdate) You can also safely ignore this warning. Mongoose will not remove the legacy `useFindAndModify: true` behavior until Mongoose 6.0. @@ -111,7 +111,7 @@ instead. By default, Mongoose 5.x calls the [MongoDB driver's `ensureIndex()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#ensureIndex). The MongoDB driver deprecated this function in favor of [`createIndex()`](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#createIndex). -Set the [`useCreateIndex` global option](/docs/api.html#mongoose_Mongoose-set) to opt in to making Mongoose use `createIndex()` instead. +Set the [`useCreateIndex` global option](api.html#mongoose_Mongoose-set) to opt in to making Mongoose use `createIndex()` instead. ```javascript mongoose.set('useCreateIndex', true); @@ -144,7 +144,7 @@ deleteMany, or bulkWrite instead. ``` To remove this deprecation warning, replace any usage of `remove()` with -`deleteMany()`, _unless_ you specify the [`single` option to `remove()`](/docs/api.html#model_Model.remove). The `single` +`deleteMany()`, _unless_ you specify the [`single` option to `remove()`](api.html#model_Model.remove). The `single` option limited `remove()` to deleting at most one document, so you should replace `remove(filter, { single: true })` with `deleteOne(filter)`. @@ -183,7 +183,7 @@ mongoose.set('useUnifiedTopology', true); ``` The `useUnifiedTopology` option removes support for several -[connection options](/docs/connections.html#options) that are +[connection options](connections.html#options) that are no longer relevant with the new topology engine: - `autoReconnect` @@ -191,16 +191,16 @@ no longer relevant with the new topology engine: - `reconnectInterval` When you enable `useUnifiedTopology`, please remove those options -from your [`mongoose.connect()`](/docs/api/mongoose.html#mongoose_Mongoose-connect) or -[`createConnection()`](/docs/api/mongoose.html#mongoose_Mongoose-createConnection) calls. +from your [`mongoose.connect()`](api/mongoose.html#mongoose_Mongoose-connect) or +[`createConnection()`](api/mongoose.html#mongoose_Mongoose-createConnection) calls. If you find any unexpected behavior, please [open up an issue on GitHub](https://github.com/Automattic/mongoose/issues/new).

          update()

          -Like `remove()`, the [`update()` function](/docs/api.html#model_Model.update) is deprecated in favor -of the more explicit [`updateOne()`](/docs/api.html#model_Model.updateOne), [`updateMany()`](/docs/api.html#model_Model.updateMany), and [`replaceOne()`](/docs/api.html#model_Model.replaceOne) functions. You should replace -`update()` with `updateOne()`, unless you use the [`multi` or `overwrite` options](/docs/api.html#model_Model.update). +Like `remove()`, the [`update()` function](api.html#model_Model.update) is deprecated in favor +of the more explicit [`updateOne()`](api.html#model_Model.updateOne), [`updateMany()`](api.html#model_Model.updateMany), and [`replaceOne()`](api.html#model_Model.replaceOne) functions. You should replace +`update()` with `updateOne()`, unless you use the [`multi` or `overwrite` options](api.html#model_Model.update). ``` collection.update is deprecated. Use updateOne, updateMany, or bulkWrite diff --git a/docs/documents.md b/docs/documents.md index 71c17b502d2..eff8ea84861 100644 --- a/docs/documents.md +++ b/docs/documents.md @@ -140,7 +140,7 @@ Read the [validation](validation.html) guide for more details. There are 2 different ways to overwrite a document (replacing all keys in the document). One way is to use the -[`Document#overwrite()` function](/docs/api/document.html#document_Document-overwrite) +[`Document#overwrite()` function](api/document.html#document_Document-overwrite) followed by `save()`. ```javascript @@ -151,7 +151,7 @@ doc.overwrite({ name: 'Jean-Luc Picard' }); await doc.save(); ``` -The other way is to use [`Model.replaceOne()`](/docs/api/model.html#model_Model.replaceOne). +The other way is to use [`Model.replaceOne()`](api/model.html#model_Model.replaceOne). ```javascript // Sets `name` and unsets all other properties @@ -161,4 +161,4 @@ await Person.replaceOne({ _id }, { name: 'Jean-Luc Picard' }); ### Next Up Now that we've covered Documents, let's take a look at -[Subdocuments](/docs/subdocs.html). +[Subdocuments](subdocs.html). diff --git a/docs/faq.md b/docs/faq.md index a7a3521858e..f8a5a3303cd 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -26,7 +26,7 @@ doc.save(); them mongoose never gets notified of the change and so doesn't know to persist the new value. There are two workarounds: [`MongooseArray#set`](api.html#types_array_MongooseArray.set) or -[`Document#markModified()`](/docs/api/document.html#document_Document-markModified). +[`Document#markModified()`](api/document.html#document_Document-markModified). ```javascript // Saves changes successfully @@ -141,7 +141,7 @@ is undefined on the underlying [POJO](guide.html#minimize). **A**. The only import syntax Mongoose supports is `import mongoose from 'mongoose'`. Syntaxes like `import * from 'mongoose'` or `import { model } from 'mongoose'` do **not** work. -The global Mongoose object stores types, [global options](/docs/api.html#mongoose_Mongoose-set), and other important +The global Mongoose object stores types, [global options](api.html#mongoose_Mongoose-set), and other important properties that Mongoose needs. When you do `import { model } from 'mongoose'`, the `this` value in `model()` is not the Mongoose global. @@ -425,7 +425,7 @@ Consider using a regex like `/^[a-f0-9]{24}$/` to test whether a string is exact **A**. In order to avoid executing a separate query for each document returned from the `find` query, Mongoose instead queries using (numDocuments * limit) as the limit. If you need the correct limit, you should use the -[perDocumentLimit](/docs/populate.html#limit-vs-perDocumentLimit) option (new in Mongoose 5.9.0). Just keep in +[perDocumentLimit](populate.html#limit-vs-perDocumentLimit) option (new in Mongoose 5.9.0). Just keep in mind that populate() will execute a separate query for each document.
          diff --git a/docs/geojson.md b/docs/geojson.md index ac2a726cb7f..f0878a75858 100644 --- a/docs/geojson.md +++ b/docs/geojson.md @@ -50,7 +50,7 @@ const citySchema = new mongoose.Schema({ }); ``` -Using [subdocuments](/docs/subdocs.html), you can define a common `pointSchema` and reuse it everywhere you want to store a GeoJSON point. +Using [subdocuments](subdocs.html), you can define a common `pointSchema` and reuse it everywhere you want to store a GeoJSON point. ```javascript const pointSchema = new mongoose.Schema({ @@ -131,7 +131,7 @@ a polygon representing the state of Colorado using [require:geojson.*driver query] ``` -Mongoose also has a [`within()` helper](/docs/api.html#query_Query-within) +Mongoose also has a [`within()` helper](api.html#query_Query-within) that's a shorthand for `$geoWithin`. ```javascript @@ -148,7 +148,7 @@ a 2dsphere index on a GeoJSON point: [require:geojson.*index$] ``` -You can also define a geospatial index using the [`Schema#index()` function](/docs/api/schema.html#schema_Schema-index) +You can also define a geospatial index using the [`Schema#index()` function](api/schema.html#schema_Schema-index) as shown below. ```javascript @@ -157,4 +157,4 @@ citySchema.index({ location: '2dsphere' }); MongoDB's [`$near` query operator](https://docs.mongodb.com/v4.0/reference/operator/query/near/#op._S_near) and [`$geoNear` aggregation stage](https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/#pipe._S_geoNear) -_require_ a 2dsphere index. \ No newline at end of file +_require_ a 2dsphere index. diff --git a/docs/guide.md b/docs/guide.md index a01f153d2b3..e599ef309f5 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -1,7 +1,7 @@ ## Schemas If you haven't yet done so, please take a minute to read the [quickstart](index.html) to get an idea of how Mongoose works. -If you are migrating from 4.x to 5.x please take a moment to read the [migration guide](/docs/migrating_to_5.html). +If you are migrating from 4.x to 5.x please take a moment to read the [migration guide](migrating_to_5.html).
          • Defining your schema
          • @@ -173,7 +173,7 @@ You can also add static functions to your model. There are two equivalent ways to add a static: - Add a function property to `schema.statics` -- Call the [`Schema#static()` function](/docs/api.html#schema_Schema-static) +- Call the [`Schema#static()` function](api.html#schema_Schema-static) ```javascript // Assign a function to the "statics" object of our animalSchema @@ -370,7 +370,7 @@ console.log(person); // { n: 'Not Val' } ``` You can also declare aliases on nested paths. It is easier to use nested -schemas and [subdocuments](/docs/subdocs.html), but you can also declare +schemas and [subdocuments](subdocs.html), but you can also declare nested path aliases inline as long as you use the full nested path `nested.myProp` as the alias. @@ -412,7 +412,7 @@ Valid options: - [toJSON](#toJSON) - [toObject](#toObject) - [typeKey](#typeKey) -- [typePojoToMixed](/docs/schematypes.html#mixed) +- [typePojoToMixed](schematypes.html#mixed) - [useNestedStrict](#useNestedStrict) - [validateBeforeSave](#validateBeforeSave) - [versionKey](#versionKey) @@ -425,9 +425,9 @@ Valid options:

            option: autoIndex

            -By default, Mongoose's [`init()` function](/docs/api.html#model_Model.init) +By default, Mongoose's [`init()` function](api.html#model_Model.init) creates all the indexes defined in your model's schema by calling -[`Model.createIndexes()`](/docs/api.html#model_Model.createIndexes) +[`Model.createIndexes()`](api.html#model_Model.createIndexes) 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 @@ -440,7 +440,7 @@ Clock.ensureIndexes(callback); ``` The `autoIndex` option is set to `true` by default. You can change this -default by setting [`mongoose.set('autoIndex', false);`](/docs/api/mongoose.html#mongoose_Mongoose-set) +default by setting [`mongoose.set('autoIndex', false);`](api/mongoose.html#mongoose_Mongoose-set)

            option: autoCreate

            @@ -465,7 +465,7 @@ const Clock = mongoose.model('Clock', schema); ``` Unlike `autoIndex`, `autoCreate` is `false` by default. You can change this -default by setting [`mongoose.set('autoCreate', true);`](/docs/api/mongoose.html#mongoose_Mongoose-set) +default by setting [`mongoose.set('autoCreate', true);`](api/mongoose.html#mongoose_Mongoose-set)

            option: bufferCommands

            @@ -528,7 +528,7 @@ const dataSchema = new Schema({..}, { collection: 'data' });

            option: discriminatorKey

            -When you define a [discriminator](/docs/discriminators.html), Mongoose adds a path to your +When you define a [discriminator](discriminators.html), Mongoose adds a path to your schema that stores which discriminator a document is an instance of. By default, Mongoose adds an `__t` path, but you can set `discriminatorKey` to overwrite this default. @@ -569,8 +569,8 @@ console.log(p.id); // undefined

            option: _id

            Mongoose assigns each of your schemas an `_id` field by default if one -is not passed into the [Schema](/docs/api.html#schema-js) constructor. -The type assigned is an [ObjectId](/docs/api.html#schema_Schema.Types) +is not passed into the [Schema](api.html#schema-js) constructor. +The type assigned is an [ObjectId](api.html#schema_Schema.Types) to coincide with MongoDB's default behavior. If you don't want an `_id` added to your schema at all, you may disable it using this option. @@ -643,7 +643,7 @@ sam.$isEmpty('inventory'); // false

            option: read

            -Allows setting [query#read](/docs/api.html#query_Query-read) options at the +Allows setting [query#read](api.html#query_Query-read) options at the schema level, providing us a way to apply default [ReadPreferences](http://docs.mongodb.org/manual/applications/replication/#replica-set-read-preference) to all queries derived from a model. @@ -811,11 +811,11 @@ console.log(m.toJSON()); // { _id: 504e0cd7dd992d9be2f20b6f, name: 'Max Headroom console.log(JSON.stringify(m)); // { "_id": "504e0cd7dd992d9be2f20b6f", "name": "Max Headroom is my name" } ``` -To see all available `toJSON/toObject` options, read [this](/docs/api.html#document_Document-toObject). +To see all available `toJSON/toObject` options, read [this](api.html#document_Document-toObject).

            option: toObject

            -Documents have a [toObject](/docs/api.html#document_Document-toObject) method +Documents have a [toObject](api.html#document_Document-toObject) 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 @@ -835,7 +835,7 @@ const m = new M({ name: 'Max Headroom' }); console.log(m); // { _id: 504e0cd7dd992d9be2f20b6f, name: 'Max Headroom is my name' } ``` -To see all available `toObject` options, read [this](/docs/api.html#document_Document-toObject). +To see all available `toObject` options, read [this](api.html#document_Document-toObject).

            option: typeKey

            @@ -935,7 +935,7 @@ const thing = new Thing({ name: 'no versioning please' }); thing.save(); // { name: 'no versioning please' } ``` -Mongoose _only_ updates the version key when you use [`save()`](/docs/api.html#document_Document-save). +Mongoose _only_ updates the version key when you use [`save()`](api.html#document_Document-save). If you use `update()`, `findOneAndUpdate()`, etc. Mongoose will **not** update the version key. As a workaround, you can use the below middleware. @@ -1229,12 +1229,12 @@ new Parent({ child: {} }).validateSync().errors;

            With ES6 Classes

            -Schemas have a [`loadClass()` method](/docs/api/schema.html#schema_Schema-loadClass) +Schemas have a [`loadClass()` method](api/schema.html#schema_Schema-loadClass) that you can use to create a Mongoose schema from an [ES6 class](https://thecodebarbarian.com/an-overview-of-es6-classes): -* [ES6 class methods](https://masteringjs.io/tutorials/fundamentals/class#methods) become [Mongoose methods](/docs/guide.html#methods) -* [ES6 class statics](https://masteringjs.io/tutorials/fundamentals/class#statics) become [Mongoose statics](/docs/guide.html#statics) -* [ES6 getters and setters](https://masteringjs.io/tutorials/fundamentals/class#getterssetters) become [Mongoose virtuals](/docs/tutorials/virtuals.html) +* [ES6 class methods](https://masteringjs.io/tutorials/fundamentals/class#methods) become [Mongoose methods](guide.html#methods) +* [ES6 class statics](https://masteringjs.io/tutorials/fundamentals/class#statics) become [Mongoose statics](guide.html#statics) +* [ES6 getters and setters](https://masteringjs.io/tutorials/fundamentals/class#getterssetters) become [Mongoose virtuals](tutorials/virtuals.html) Here's an example of using `loadClass()` to create a schema from an ES6 class: @@ -1277,4 +1277,4 @@ of use cases, including e-commerce, wikis, and appointment bookings.

            Next Up

            -Now that we've covered `Schemas`, let's take a look at [SchemaTypes](/docs/schematypes.html). +Now that we've covered `Schemas`, let's take a look at [SchemaTypes](schematypes.html). diff --git a/docs/guides.md b/docs/guides.md index c8196bfa341..5cdf9a1c06c 100644 --- a/docs/guides.md +++ b/docs/guides.md @@ -5,43 +5,42 @@ integrating Mongoose with external tools and frameworks. ### Mongoose Core Concepts -* [Schemas](/docs/guide.html) -* [SchemaTypes](/docs/schematypes.html) -* [Connections](/docs/connections.html) -* [Models](/docs/models.html) -* [Documents](/docs/documents.html) -* [Subdocuments](/docs/subdocs.html) -* [Queries](/docs/queries.html) -* [Validation](/docs/validation.html) -* [Middleware](/docs/middleware.html) -* [Populate](/docs/populate.html) -* [Discriminators](/docs/discriminators.html) -* [Plugins](/docs/plugins.html) -* [Faster Mongoose Queries With Lean](/docs/tutorials/lean.html) -* [Query Casting](/docs/tutorials/query_casting.html) -* [findOneAndUpdate](/docs/tutorials/findoneandupdate.html) -* [Getters and Setters](/docs/tutorials/getters-setters.html) -* [Virtuals](/docs/tutorials/virtuals.html) +* [Schemas](guide.html) +* [SchemaTypes](schematypes.html) +* [Connections](connections.html) +* [Models](models.html) +* [Documents](documents.html) +* [Subdocuments](subdocs.html) +* [Queries](queries.html) +* [Validation](validation.html) +* [Middleware](middleware.html) +* [Populate](populate.html) +* [Discriminators](discriminators.html) +* [Plugins](plugins.html) +* [Faster Mongoose Queries With Lean](tutorials/lean.html) +* [Query Casting](tutorials/query_casting.html) +* [findOneAndUpdate](tutorials/findoneandupdate.html) +* [Getters and Setters](tutorials/getters-setters.html) +* [Virtuals](tutorials/virtuals.html) ### Advanced Topics -* [Working with Dates](/docs/tutorials/dates.html) -* [Custom Casting For Built-in Types](/docs/tutorials/custom-casting.html) -* [Custom SchemaTypes](/docs/customschematypes.html) +* [Working with Dates](tutorials/dates.html) +* [Custom Casting For Built-in Types](tutorials/custom-casting.html) +* [Custom SchemaTypes](customschematypes.html) ### Integrations -* [Promises](/docs/promises.html) -* [AWS Lambda](/docs/lambda.html) -* [Browser Library](/docs/browser.html) -* [GeoJSON](/docs/geojson.html) -* [Transactions](/docs/transactions.html) -* [MongoDB Driver Deprecation Warnings](/docs/deprecations.html) -* [Testing with Jest](/docs/jest.html) -* [SSL Connections](/docs/tutorials/ssl.html) +* [Promises](promises.html) +* [AWS Lambda](lambda.html) +* [Browser Library](browser.html) +* [GeoJSON](geojson.html) +* [Transactions](transactions.html) +* [MongoDB Driver Deprecation Warnings](deprecations.html) +* [Testing with Jest](jest.html) +* [SSL Connections](tutorials/ssl.html) ### Migration Guides -* [Mongoose 4.x to 5.x](/docs/migrating_to_5.html) -* [Mongoose 3.x to 4.x](/docs/migration.html) - +* [Mongoose 4.x to 5.x](migrating_to_5.html) +* [Mongoose 3.x to 4.x](migration.html) diff --git a/docs/index.md b/docs/index.md index 69fdf994253..1bec43b6fc4 100644 --- a/docs/index.md +++ b/docs/index.md @@ -46,7 +46,7 @@ db.once('open', function() { Once our connection opens, our callback will be called. For brevity, let's assume that all following code is within this callback. -With Mongoose, everything is derived from a [Schema](/docs/guide.html). +With Mongoose, everything is derived from a [Schema](guide.html). Let's get a reference to it and define our kittens. ```javascript @@ -55,7 +55,7 @@ const kittySchema = new mongoose.Schema({ }); ``` -So far so good. We've got a schema with one property, `name`, which will be a `String`. The next step is compiling our schema into a [Model](/docs/models.html). +So far so good. We've got a schema with one property, `name`, which will be a `String`. The next step is compiling our schema into a [Model](models.html). ```javascript const Kitten = mongoose.model('Kitten', kittySchema); @@ -94,7 +94,7 @@ fluffy.speak(); // "Meow name is fluffy" ``` We have talking kittens! But we still haven't saved anything to MongoDB. -Each document can be saved to the database by calling its [save](/docs/api.html#model_Model-save) method. The first argument to the callback will be an error if any occurred. +Each document can be saved to the database by calling its [save](api.html#model_Model-save) method. The first argument to the callback will be an error if any occurred. ```javascript fluffy.save(function (err, fluffy) { @@ -104,7 +104,7 @@ Each document can be saved to the database by calling its [save](/docs/api.html# ``` Say time goes by and we want to display all the kittens we've seen. -We can access all of the kitten documents through our Kitten [model](/docs/models.html). +We can access all of the kitten documents through our Kitten [model](models.html). ```javascript Kitten.find(function (err, kittens) { @@ -114,7 +114,7 @@ Kitten.find(function (err, kittens) { ``` We just logged all of the kittens in our db to the console. -If we want to filter our kittens by name, Mongoose supports MongoDBs rich [querying](/docs/queries.html) syntax. +If we want to filter our kittens by name, Mongoose supports MongoDBs rich [querying](queries.html) syntax. ```javascript Kitten.find({ name: /^fluff/ }, callback); diff --git a/docs/lambda.md b/docs/lambda.md index 61c060828f8..0c94ec8ebc6 100644 --- a/docs/lambda.md +++ b/docs/lambda.md @@ -115,5 +115,5 @@ exports.connect = async function() { *Want to learn how to check whether your favorite JavaScript frameworks, like [Express](http://expressjs.com/) or [React](https://reactjs.org/), work with async/await? Spoiler alert: neither Express nor React support async/await. Chapter 4 of Mastering Async/Await explains the basic principles for determining whether a framework supports async/await. [Get your copy!](http://asyncawait.net/?utm_source=mongoosejs&utm_campaign=lambda)* - + diff --git a/docs/middleware.md b/docs/middleware.md index c5b2d5bbb76..dfc0c85467e 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -26,12 +26,12 @@ of middleware: document middleware, model middleware, aggregate middleware, and Document middleware is supported for the following document functions. In document middleware functions, `this` refers to the document. -* [validate](/docs/api/document.html#document_Document-validate) -* [save](/docs/api/model.html#model_Model-save) -* [remove](/docs/api/model.html#model_Model-remove) -* [updateOne](/docs/api/document.html#document_Document-updateOne) -* [deleteOne](/docs/api/model.html#model_Model-deleteOne) -* [init](/docs/api/document.html#document_Document-init) (note: init hooks are [synchronous](#synchronous)) +* [validate](api/document.html#document_Document-validate) +* [save](api/model.html#model_Model-save) +* [remove](api/model.html#model_Model-remove) +* [updateOne](api/document.html#document_Document-updateOne) +* [deleteOne](api/model.html#model_Model-deleteOne) +* [init](api/document.html#document_Document-init) (note: init hooks are [synchronous](#synchronous)) Query middleware is supported for the following Model and Query functions. In query middleware functions, `this` refers to the query. @@ -178,7 +178,7 @@ error `err1` and then throw an error `err2`, mongoose will report `err1`.

            Post middleware

            -[post](/docs/api.html#schema_Schema-post) middleware are executed _after_ +[post](api.html#schema_Schema-post) middleware are executed _after_ the hooked method and all of its `pre` middleware have completed. ```javascript @@ -221,7 +221,7 @@ schema.post('save', function(doc, next) {

            Define Middleware Before Compiling Models

            -Calling `pre()` or `post()` after [compiling a model](/docs/models.html#compiling) +Calling `pre()` or `post()` after [compiling a model](models.html#compiling) does **not** work in Mongoose in general. For example, the below `pre('save')` middleware will not fire. @@ -238,8 +238,8 @@ schema.pre('save', () => console.log('Hello from pre save')); new User({ name: 'test' }).save(); ``` -This means that you must add all middleware and [plugins](/docs/plugins.html) -**before** calling [`mongoose.model()`](/docs/api/mongoose.html#mongoose_Mongoose-model). +This means that you must add all middleware and [plugins](plugins.html) +**before** calling [`mongoose.model()`](api/mongoose.html#mongoose_Mongoose-model). The below script will print out "Hello from pre save": ```javascript @@ -256,7 +256,7 @@ new User({ name: 'test' }).save(); As a consequence, be careful about exporting Mongoose models from the same file that you define your schema. If you choose to use this pattern, you -must define [global plugins](/docs/api/mongoose.html#mongoose_Mongoose-plugin) +must define [global plugins](api/mongoose.html#mongoose_Mongoose-plugin) **before** calling `require()` on your model file. ```javascript @@ -304,10 +304,10 @@ doc.remove(); Model.remove(); ``` -You can pass options to [`Schema.pre()`](/docs/api.html#schema_Schema-pre) -and [`Schema.post()`](/docs/api.html#schema_Schema-post) to switch whether -Mongoose calls your `remove()` hook for [`Document.remove()`](/docs/api.html#model_Model-remove) -or [`Model.remove()`](/docs/api.html#model_Model.remove). Note here that you need to set both `document` and `query` properties in the passed object: +You can pass options to [`Schema.pre()`](api.html#schema_Schema-pre) +and [`Schema.post()`](api.html#schema_Schema-post) to switch whether +Mongoose calls your `remove()` hook for [`Document.remove()`](api.html#model_Model-remove) +or [`Model.remove()`](api.html#model_Model.remove). Note here that you need to set both `document` and `query` properties in the passed object: ```javascript // Only document middleware @@ -372,7 +372,7 @@ schema.pre('findOneAndUpdate', async function() { However, if you define `pre('updateOne')` document middleware, `this` will be the document being updated. That's because `pre('updateOne')` -document middleware hooks into [`Document#updateOne()`](/docs/api/document.html#document_Document-updateOne) +document middleware hooks into [`Document#updateOne()`](api/document.html#document_Document-updateOne) rather than `Query#updateOne()`. ```javascript @@ -500,4 +500,4 @@ rejections.

            Next Up

            Now that we've covered middleware, let's take a look at Mongoose's approach -to faking JOINs with its query [population](/docs/populate.html) helper. +to faking JOINs with its query [population](populate.html) helper. diff --git a/docs/migrating_to_5.md b/docs/migrating_to_5.md index 53048ab69e9..f3871363017 100644 --- a/docs/migrating_to_5.md +++ b/docs/migrating_to_5.md @@ -465,7 +465,7 @@ In Mongoose 5.x, the above code will correctly overwrite `'baseball'` with `{ $n Mongoose 5.x uses version 3.x of the [MongoDB Node.js driver](http://npmjs.com/package/mongodb). MongoDB driver 3.x changed the format of -the result of [`bulkWrite()` calls](/docs/api.html#model_Model.bulkWrite) so there is no longer a top-level `nInserted`, `nModified`, etc. property. The new result object structure is [described here](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult). +the result of [`bulkWrite()` calls](api.html#model_Model.bulkWrite) so there is no longer a top-level `nInserted`, `nModified`, etc. property. The new result object structure is [described here](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult). ```javascript const Model = mongoose.model('Test', new Schema({ name: String })); @@ -545,4 +545,4 @@ If this is blocking you from upgrading, you can set the `tlsInsecure` option to ```javascript mongoose.connect(uri, { tlsInsecure: false }); // Opt out of additional SSL validation -``` \ No newline at end of file +``` diff --git a/docs/models.md b/docs/models.md index a758667b50b..e4d2284013c 100644 --- a/docs/models.md +++ b/docs/models.md @@ -160,4 +160,4 @@ The [API docs](api.html#model_Model) cover many additional methods available lik ### Next Up -Now that we've covered `Models`, let's take a look at [Documents](/docs/documents.html). +Now that we've covered `Models`, let's take a look at [Documents](documents.html). diff --git a/docs/plugins.md b/docs/plugins.md index 23a015b4ff7..e68f88270db 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -65,8 +65,8 @@ const Player = mongoose.model('Player', playerSchema);

            Apply Plugins Before Compiling Models

            -Because many plugins rely on [middleware](/docs/middleware.html), you should make sure to apply plugins **before** -you call `mongoose.model()` or `conn.model()`. Otherwise, [any middleware the plugin registers won't get applied](/docs/middleware.html#defining). +Because many plugins rely on [middleware](middleware.html), you should make sure to apply plugins **before** +you call `mongoose.model()` or `conn.model()`. Otherwise, [any middleware the plugin registers won't get applied](middleware.html#defining). ```javascript // loadedAt.js @@ -101,8 +101,8 @@ gameSchema.plugin(loadedAtPlugin); The Mongoose team maintains several plugins that add cool new features to Mongoose. Here's a couple: -* [mongoose-autopopulate](http://plugins.mongoosejs.io/plugins/autopopulate): Always [`populate()`](/docs/populate.html) certain fields in your Mongoose schemas. -* [mongoose-lean-virtuals](http://plugins.mongoosejs.io/plugins/lean-virtuals): Attach virtuals to the results of Mongoose queries when using [`.lean()`](/docs/api.html#query_Query-lean). +* [mongoose-autopopulate](http://plugins.mongoosejs.io/plugins/autopopulate): Always [`populate()`](populate.html) certain fields in your Mongoose schemas. +* [mongoose-lean-virtuals](http://plugins.mongoosejs.io/plugins/lean-virtuals): Attach virtuals to the results of Mongoose queries when using [`.lean()`](api.html#query_Query-lean). * [mongoose-cast-aggregation](https://www.npmjs.com/package/mongoose-cast-aggregation) You can find a full list of officially supported plugins on [Mongoose's plugins search site](https://plugins.mongoosejs.io/). diff --git a/docs/populate.md b/docs/populate.md index a2ddbece18b..b613104e3b2 100644 --- a/docs/populate.md +++ b/docs/populate.md @@ -137,7 +137,7 @@ story.populated('author'); // undefined ``` A common reason for checking whether a path is populated is getting the `author` -id. However, for your convenience, Mongoose adds a [`_id` getter to ObjectId instances](/docs/api/mongoose.html#mongoose_Mongoose-set) +id. However, for your convenience, Mongoose adds a [`_id` getter to ObjectId instances](api/mongoose.html#mongoose_Mongoose-set) so you can use `story.author._id` regardless of whether `author` is populated. ```javascript @@ -379,7 +379,7 @@ the array. If you have an existing mongoose document and want to populate some of its paths, you can use the [Document#populate()](api.html#document_Document-populate) method. -Just make sure you call [`Document#execPopulate()`](/docs/api/document.html#document_Document-execPopulate) +Just make sure you call [`Document#execPopulate()`](api/document.html#document_Document-execPopulate) to execute the `populate()`. ```javascript @@ -474,7 +474,7 @@ This is known as a "cross-database populate," because it enables you to populate across MongoDB databases and even across MongoDB instances. If you don't have access to the model instance when defining your `eventSchema`, -you can also pass [the model instance as an option to `populate()`](/docs/api/model.html#model_Model.populate). +you can also pass [the model instance as an option to `populate()`](api/model.html#model_Model.populate). ```javascript const events = await Event. @@ -709,7 +709,7 @@ doc.numMembers; // 2

            Populating Maps

            -[Maps](/docs/schematypes.html#maps) are a type that represents an object with arbitrary +[Maps](schematypes.html#maps) are a type that represents an object with arbitrary string keys. For example, in the below schema, `members` is a map from strings to ObjectIds. ```javascript @@ -813,4 +813,4 @@ MySchema.post('save', function(doc, next) { ### Next Up -Now that we've covered `populate()`, let's take a look at [discriminators](/docs/discriminators.html). +Now that we've covered `populate()`, let's take a look at [discriminators](discriminators.html). diff --git a/docs/promises.md b/docs/promises.md index cc86b1e602f..9f52f32b13b 100644 --- a/docs/promises.md +++ b/docs/promises.md @@ -71,5 +71,5 @@ ES6-style promise constructor and mongoose will use it.

            - + diff --git a/docs/queries.md b/docs/queries.md index ad2fa651ed1..c6c158ebded 100644 --- a/docs/queries.md +++ b/docs/queries.md @@ -5,21 +5,21 @@ for [CRUD operations](https://en.wikipedia.org/wiki/Create,_read,_update_and_del Each of these functions returns a [mongoose `Query` object](http://mongoosejs.com/docs/api.html#Query). -- [`Model.deleteMany()`](/docs/api.html#model_Model.deleteMany) -- [`Model.deleteOne()`](/docs/api.html#model_Model.deleteOne) -- [`Model.find()`](/docs/api.html#model_Model.find) -- [`Model.findById()`](/docs/api.html#model_Model.findById) -- [`Model.findByIdAndDelete()`](/docs/api.html#model_Model.findByIdAndDelete) -- [`Model.findByIdAndRemove()`](/docs/api.html#model_Model.findByIdAndRemove) -- [`Model.findByIdAndUpdate()`](/docs/api.html#model_Model.findByIdAndUpdate) -- [`Model.findOne()`](/docs/api.html#model_Model.findOne) -- [`Model.findOneAndDelete()`](/docs/api.html#model_Model.findOneAndDelete) -- [`Model.findOneAndRemove()`](/docs/api.html#model_Model.findOneAndRemove) -- [`Model.findOneAndReplace()`](/docs/api.html#model_Model.findOneAndReplace) -- [`Model.findOneAndUpdate()`](/docs/api.html#model_Model.findOneAndUpdate) -- [`Model.replaceOne()`](/docs/api.html#model_Model.replaceOne) -- [`Model.updateMany()`](/docs/api.html#model_Model.updateMany) -- [`Model.updateOne()`](/docs/api.html#model_Model.updateOne) +- [`Model.deleteMany()`](api.html#model_Model.deleteMany) +- [`Model.deleteOne()`](api.html#model_Model.deleteOne) +- [`Model.find()`](api.html#model_Model.find) +- [`Model.findById()`](api.html#model_Model.findById) +- [`Model.findByIdAndDelete()`](api.html#model_Model.findByIdAndDelete) +- [`Model.findByIdAndRemove()`](api.html#model_Model.findByIdAndRemove) +- [`Model.findByIdAndUpdate()`](api.html#model_Model.findByIdAndUpdate) +- [`Model.findOne()`](api.html#model_Model.findOne) +- [`Model.findOneAndDelete()`](api.html#model_Model.findOneAndDelete) +- [`Model.findOneAndRemove()`](api.html#model_Model.findOneAndRemove) +- [`Model.findOneAndReplace()`](api.html#model_Model.findOneAndReplace) +- [`Model.findOneAndUpdate()`](api.html#model_Model.findOneAndUpdate) +- [`Model.replaceOne()`](api.html#model_Model.replaceOne) +- [`Model.updateMany()`](api.html#model_Model.updateMany) +- [`Model.updateOne()`](api.html#model_Model.updateOne) A mongoose query can be executed in one of two ways. First, if you pass in a `callback` function, Mongoose will execute the query asynchronously @@ -212,7 +212,7 @@ However, just because you can use `aggregate()` doesn't mean you should. In general, you should use queries where possible, and only use `aggregate()` when you absolutely need to. -Unlike query results, Mongoose does **not** [`hydrate()`](/docs/api/model.html#model_Model.hydrate) +Unlike query results, Mongoose does **not** [`hydrate()`](api/model.html#model_Model.hydrate) aggregation results. Aggregation results are always POJOs, not Mongoose documents. @@ -223,7 +223,7 @@ docs[0] instanceof mongoose.Document; // false ``` Also, unlike query filters, Mongoose also doesn't -[cast](/docs/tutorials/query_casting.html) aggregation pipelines. That means +[cast](tutorials/query_casting.html) aggregation pipelines. That means you're responsible for ensuring the values you pass in to an aggregation pipeline have the correct type. @@ -242,4 +242,4 @@ const aggRes = await Person.aggregate([{ $match: { _id: idString } }])

            Next Up

            -Now that we've covered `Queries`, let's take a look at [Validation](/docs/validation.html). +Now that we've covered `Queries`, let's take a look at [Validation](validation.html). diff --git a/docs/schematypes.md b/docs/schematypes.md index 51552bdb52c..c636685985c 100644 --- a/docs/schematypes.md +++ b/docs/schematypes.md @@ -134,7 +134,7 @@ const schema = new Schema({ }); ``` -As a consequence, [you need a little extra work to define a property named `type` in your schema](/docs/faq.html#type-key). +As a consequence, [you need a little extra work to define a property named `type` in your schema](faq.html#type-key). For example, suppose you're building a stock portfolio app, and you want to store the asset's `type` (stock, bond, ETF, etc.). Naively, you might define your schema as shown below: @@ -216,7 +216,7 @@ types. * `set`: function, defines a custom setter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). * `alias`: string, mongoose >= 4.10.0 only. Defines a [virtual](guide.html#virtuals) with the given name that gets/sets this path. * `immutable`: boolean, defines path as immutable. Mongoose prevents you from changing immutable paths unless the parent document has `isNew: true`. -* `transform`: function, Mongoose calls this function when you call [`Document#toJSON()`](/docs/api/document.html#document_Document-toJSON) function, including when you [`JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript) a document. +* `transform`: function, Mongoose calls this function when you call [`Document#toJSON()`](api/document.html#document_Document-toJSON) function, including when you [`JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript) a document. ```javascript const numberSchema = new Schema({ @@ -268,14 +268,14 @@ const schema2 = new Schema({ * `enum`: Array, creates a [validator](validation.html) that checks if the value is in the given array. * `minLength`: Number, creates a [validator](validation.html) that checks if the value length is not less than the given number * `maxLength`: Number, creates a [validator](validation.html) that checks if the value length is not greater than the given number -* `populate`: Object, sets default [populate options](/docs/populate.html#query-conditions) +* `populate`: Object, sets default [populate options](populate.html#query-conditions)
            Number
            * `min`: Number, creates a [validator](validation.html) that checks if the value is greater than or equal to the given minimum. * `max`: Number, creates a [validator](validation.html) that checks if the value is less than or equal to the given maximum. * `enum`: Array, creates a [validator](validation.html) that checks if the value is strictly equal to one of the values in the given array. -* `populate`: Object, sets default [populate options](/docs/populate.html#query-conditions) +* `populate`: Object, sets default [populate options](populate.html#query-conditions)
            Date
            @@ -284,7 +284,7 @@ const schema2 = new Schema({
            ObjectId
            -* `populate`: Object, sets default [populate options](/docs/populate.html#query-conditions) +* `populate`: Object, sets default [populate options](populate.html#query-conditions)

            Usage Notes

            @@ -339,7 +339,7 @@ call it and assign the returned value to the path. The values `null` and `undefined` are not cast. NaN, strings that cast to NaN, arrays, and objects that don't have a `valueOf()` function -will all result in a [CastError](/docs/validation.html#cast-errors) once validated, meaning that it will not throw on initialization, only when validated. +will all result in a [CastError](validation.html#cast-errors) once validated, meaning that it will not throw on initialization, only when validated.

            Dates

            @@ -463,7 +463,7 @@ Mongoose casts the below values to `false`: * `'0'` * `'no'` -Any other value causes a [CastError](/docs/validation.html#cast-errors). +Any other value causes a [CastError](validation.html#cast-errors). You can modify what values Mongoose converts to true or false using the `convertToTrue` and `convertToFalse` properties, which are [JavaScript sets](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). @@ -586,7 +586,7 @@ Map types are stored as [BSON objects in MongoDB](https://en.wikipedia.org/wiki/ Keys in a BSON object are ordered, so this means the [insertion order](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Description) property of maps is maintained. -Mongoose supports a special `$*` syntax to [populate](/docs/populate.html) all elements in a map. +Mongoose supports a special `$*` syntax to [populate](populate.html) all elements in a map. For example, suppose your `socialMediaHandles` map contains a `ref`: ```javascript diff --git a/docs/subdocs.md b/docs/subdocs.md index 4f34f7daa75..395616d8d34 100644 --- a/docs/subdocs.md +++ b/docs/subdocs.md @@ -145,7 +145,7 @@ console.log(doc2.child); // Prints 'MongooseDocument { undefined }' doc2.child.name = 'test'; // Works ``` -Secondly, in Mongoose 5, [`Document#set()`](/docs/api/document.html#document_Document-set) +Secondly, in Mongoose 5, [`Document#set()`](api/document.html#document_Document-set) merges when you call it on a nested path, but overwrites when you call it on a subdocument. @@ -370,7 +370,7 @@ const schema = new Schema({ ``` Surprisingly, declaring `nested` with an object `type` makes `nested` -into a path of type [Mixed](/docs/schematypes.html#mixed). To instead +into a path of type [Mixed](schematypes.html#mixed). To instead make Mongoose automatically convert `type: { prop: String }` into `type: new Schema({ prop: String })`, set the `typePojoToMixed` option to `false`. diff --git a/docs/transactions.md b/docs/transactions.md index 9fe2d5129db..1a34151e455 100644 --- a/docs/transactions.md +++ b/docs/transactions.md @@ -12,8 +12,8 @@ If you haven't already, import mongoose: import mongoose from 'mongoose'; ``` -To create a transaction, you first need to create a session using or [`Mongoose#startSession`](/docs/api/mongoose.html#mongoose_Mongoose-startSession) -or [`Connection#startSession()`](/docs/api/connection.html#connection_Connection-startSession). +To create a transaction, you first need to create a session using or [`Mongoose#startSession`](api/mongoose.html#mongoose_Mongoose-startSession) +or [`Connection#startSession()`](api/connection.html#connection_Connection-startSession). ```javascript // Using Mongoose's default connection @@ -49,11 +49,11 @@ function handles resetting a document if you `save()` that document in a transac

            With Mongoose Documents and save()

            -If you get a [Mongoose document](/docs/documents.html) from [`findOne()`](/docs/api.html#findone_findOne) -or [`find()`](/docs/api.html#find_find) using a session, the document will -keep a reference to the session and use that session for [`save()`](/docs/api.html#document_Document-save). +If you get a [Mongoose document](documents.html) from [`findOne()`](api.html#findone_findOne) +or [`find()`](api.html#find_find) using a session, the document will +keep a reference to the session and use that session for [`save()`](api.html#document_Document-save). -To get/set the session associated with a given document, use [`doc.$session()`](/docs/api.html#document_Document-$session). +To get/set the session associated with a given document, use [`doc.$session()`](api.html#document_Document-$session). ```javascript [require:transactions.*save] @@ -62,8 +62,8 @@ To get/set the session associated with a given document, use [`doc.$session()`](

            With the Aggregation Framework

            The `Model.aggregate()` function also supports transactions. Mongoose -aggregations have a [`session()` helper](/docs/api.html#aggregate_Aggregate-session) -that sets the [`session` option](/docs/api.html#aggregate_Aggregate-option). +aggregations have a [`session()` helper](api.html#aggregate_Aggregate-session) +that sets the [`session` option](api.html#aggregate_Aggregate-option). Below is an example of executing an aggregation within a transaction. ```javascript diff --git a/docs/tutorials/dates.md b/docs/tutorials/dates.md index 582ed41ba6c..4d1dffefcb0 100644 --- a/docs/tutorials/dates.md +++ b/docs/tutorials/dates.md @@ -13,7 +13,7 @@ const userSchema = new mongoose.Schema({ const User = mongoose.model('User', userSchema); ``` -When you create a user [document](/docs/documents.html), Mongoose will cast +When you create a user [document](../documents.html), Mongoose will cast the value to a [native JavaScript date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) using the [`Date()` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax). @@ -21,7 +21,7 @@ using the [`Date()` constructor](https://developer.mozilla.org/en-US/docs/Web/Ja [require:Date Tutorial.*Example 1.2] ``` -An invalid date will lead to a `CastError` when you [validate the document](/docs/validation.html). +An invalid date will lead to a `CastError` when you [validate the document](../validation.html). ```javascript [require:Date Tutorial.*Example 1.3] diff --git a/docs/tutorials/findoneandupdate.md b/docs/tutorials/findoneandupdate.md index 48f997231fe..11373945084 100644 --- a/docs/tutorials/findoneandupdate.md +++ b/docs/tutorials/findoneandupdate.md @@ -1,6 +1,6 @@ # How to Use `findOneAndUpdate()` in Mongoose -The [`findOneAndUpdate()` function in Mongoose](/docs/api.html#query_Query-findOneAndUpdate) has a wide variety of use cases. [You should use `save()` to update documents where possible](https://masteringjs.io/tutorials/mongoose/update), but there are some cases where you need to use `findOneAndUpdate()`. In this tutorial, you'll see how to use `findOneAndUpdate()`, and learn when you need to use it. +The [`findOneAndUpdate()` function in Mongoose](../api.html#query_Query-findOneAndUpdate) has a wide variety of use cases. [You should use `save()` to update documents where possible](https://masteringjs.io/tutorials/mongoose/update), but there are some cases where you need to use `findOneAndUpdate()`. In this tutorial, you'll see how to use `findOneAndUpdate()`, and learn when you need to use it. * [Getting Started](#getting-started) * [Atomic Updates](#atomic-updates) @@ -36,7 +36,7 @@ which has the same option. With the exception of an [unindexed upsert](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/#upsert-with-unique-index), [`findOneAndUpdate()` is atomic](https://docs.mongodb.com/manual/core/write-operations-atomicity/#atomicity). That means you can assume the document doesn't change between when MongoDB finds the document and when it updates the document, _unless_ you're doing an [upsert](#upsert). -For example, if you're using `save()` to update a document, the document can change in MongoDB in between when you load the document using `findOne()` and when you save the document using `save()` as show below. For many use cases, the `save()` race condition is a non-issue. But you can work around it with `findOneAndUpdate()` (or [transactions](/docs/transactions.html)) if you need to. +For example, if you're using `save()` to update a document, the document can change in MongoDB in between when you load the document using `findOne()` and when you save the document using `save()` as show below. For many use cases, the `save()` race condition is a non-issue. But you can work around it with `findOneAndUpdate()` (or [transactions](../transactions.html)) if you need to. ```javascript [require:Tutorial.*findOneAndUpdate.*save race condition] @@ -76,4 +76,4 @@ Here's what the `res` object from the above example looks like: __v: 0, age: 29 }, ok: 1 } -``` \ No newline at end of file +``` diff --git a/docs/tutorials/getters-setters.md b/docs/tutorials/getters-setters.md index c26606db0e1..dc94fb6a41b 100644 --- a/docs/tutorials/getters-setters.md +++ b/docs/tutorials/getters-setters.md @@ -1,6 +1,6 @@ # Getters/Setters in Mongoose -Mongoose getters and setters allow you to execute custom logic when getting or setting a property on a [Mongoose document](/docs/documents.html). Getters let you transform data in MongoDB into a more user friendly form, and setters let you transform user data before it gets to MongoDB. +Mongoose getters and setters allow you to execute custom logic when getting or setting a property on a [Mongoose document](../documents.html). Getters let you transform data in MongoDB into a more user friendly form, and setters let you transform user data before it gets to MongoDB. ## Getters @@ -37,7 +37,7 @@ const userSchema = new Schema({ }, { toJSON: { getters: false } }); ``` -To skip getters on a one-off basis, use [`user.get()` with the `getters` option set to `false`](/docs/api/document.html#document_Document-get) as shown below. +To skip getters on a one-off basis, use [`user.get()` with the `getters` option set to `false`](../api/document.html#document_Document-get) as shown below. ```javascript [require:getters/setters.*getters.*skip] @@ -53,7 +53,7 @@ make it easy to search without worrying about case. Below is an example [require:getters/setters.*setters.*basic] ``` -Mongoose also runs setters on update operations, like [`updateOne()`](/docs/api/query.html#query_Query-updateOne). Mongoose will +Mongoose also runs setters on update operations, like [`updateOne()`](../api/query.html#query_Query-updateOne). Mongoose will [upsert a document](https://masteringjs.io/tutorials/mongoose/upsert) with a lowercased `email` in the below example. diff --git a/docs/tutorials/lean.md b/docs/tutorials/lean.md index f355b9e2d6e..8bd67abb618 100644 --- a/docs/tutorials/lean.md +++ b/docs/tutorials/lean.md @@ -1,9 +1,9 @@ # Faster Mongoose Queries With Lean -The [lean option](/docs/api.html#query_Query-lean) tells Mongoose to skip -[hydrating](/docs/api.html#model_Model.hydrate) the result documents. This +The [lean option](../api.html#query_Query-lean) tells Mongoose to skip +[hydrating](../api.html#model_Model.hydrate) the result documents. This makes queries faster and less memory intensive, but the result documents are -plain old JavaScript objects (POJOs), **not** [Mongoose documents](/docs/documents.html). +plain old JavaScript objects (POJOs), **not** [Mongoose documents](../documents.html). In this tutorial, you'll learn more about the tradeoffs of using `lean()`. * [Using Lean](#using-lean) @@ -14,7 +14,7 @@ In this tutorial, you'll learn more about the tradeoffs of using `lean()`.

            Using Lean

            By default, Mongoose queries return an instance of the -[Mongoose `Document` class](/docs/api.html#Document). Documents are much +[Mongoose `Document` class](../api.html#Document). Documents are much heavier than vanilla JavaScript objects, because they have a lot of internal state for change tracking. Enabling the `lean` option tells Mongoose to skip instantiating a full Mongoose document and just give you the POJO. @@ -54,7 +54,7 @@ and virtuals don't run if you enable `lean`.

            Lean and Populate

            -[Populate](/docs/populate.html) works with `lean()`. If you +[Populate](../populate.html) works with `lean()`. If you use both `populate()` and `lean()`, the `lean` option propagates to the populated documents as well. In the below example, both the top-level 'Group' documents and the populated 'Person' documents will be lean. @@ -63,7 +63,7 @@ populated documents as well. In the below example, both the top-level [require:Lean Tutorial.*conventional populate] ``` -[Virtual populate](/docs/populate.html#populate-virtuals) also works with lean. +[Virtual populate](../populate.html#populate-virtuals) also works with lean. ```javascript [require:Lean Tutorial.*virtual populate] @@ -74,9 +74,9 @@ populated documents as well. In the below example, both the top-level If you're executing a query and sending the results without modification to, say, an [Express response](http://expressjs.com/en/4x/api.html#res), you should use lean. In general, if you do not modify the query results and do not use -[custom getters](/docs/api.html#schematype_SchemaType-get), you should use +[custom getters](../api.html#schematype_SchemaType-get), you should use `lean()`. If you modify the query results or rely on features like getters -or [transforms](/docs/api.html#document_Document-toObject), you should not +or [transforms](../api.html#document_Document-toObject), you should not use `lean()`. Below is an example of an [Express route](http://expressjs.com/en/guide/routing.html) @@ -118,8 +118,8 @@ to add virtuals to your lean query results. ## Plugins -Using `lean()` bypasses all Mongoose features, including [virtuals](/docs/tutorials/virtuals.html), [getters/setters](/docs/tutorials/getters-setters.html), -and [defaults](/docs/api.html#schematype_SchemaType-default). If you want to +Using `lean()` bypasses all Mongoose features, including [virtuals](virtuals.html), [getters/setters](getters-setters.html), +and [defaults](../api.html#schematype_SchemaType-default). If you want to use these features with `lean()`, you need to use the corresponding plugin: - [mongoose-lean-virtuals](https://plugins.mongoosejs.io/plugins/lean-virtuals) @@ -139,4 +139,4 @@ schema.virtual('lowercase', function() { this.name; // Works this.get('name'); // Crashes because `this` is not a Mongoose document. }); -``` \ No newline at end of file +``` diff --git a/docs/tutorials/ssl.md b/docs/tutorials/ssl.md index 4595c2a29dd..b3dc4ee2209 100644 --- a/docs/tutorials/ssl.md +++ b/docs/tutorials/ssl.md @@ -1,6 +1,6 @@ # SSL Connections -Mongoose supports connecting to [MongoDB clusters that require SSL connections](https://docs.mongodb.com/manual/tutorial/configure-ssl/). Setting the `ssl` option to `true` in [`mongoose.connect()`](/docs/api/mongoose.html#mongoose_Mongoose-connect) or your connection string is enough to connect to a MongoDB cluster using SSL: +Mongoose supports connecting to [MongoDB clusters that require SSL connections](https://docs.mongodb.com/manual/tutorial/configure-ssl/). Setting the `ssl` option to `true` in [`mongoose.connect()`](../api/mongoose.html#mongoose_Mongoose-connect) or your connection string is enough to connect to a MongoDB cluster using SSL: ```javascript mongoose.connect('mongodb://localhost:27017/test', { ssl: true }); @@ -67,4 +67,4 @@ MongooseServerSelectionError: Hostname/IP does not match certificate's altnames: ``` The SSL certificate's [common name](https://knowledge.digicert.com/solution/SO7239.html) **must** line up with the host name -in your connection string. If the SSL certificate is for `hostname2.mydomain.com`, your connection string must connect to `hostname2.mydomain.com`, not any other hostname or IP address that may be equivalent to `hostname2.mydomain.com`. For replica sets, this also means that the SSL certificate's common name must line up with the [machine's `hostname`](/docs/connections.html#replicaset-hostnames). +in your connection string. If the SSL certificate is for `hostname2.mydomain.com`, your connection string must connect to `hostname2.mydomain.com`, not any other hostname or IP address that may be equivalent to `hostname2.mydomain.com`. For replica sets, this also means that the SSL certificate's common name must line up with the [machine's `hostname`](../connections.html#replicaset-hostnames). diff --git a/docs/tutorials/virtuals.md b/docs/tutorials/virtuals.md index 5a3052e189c..9eba9dbbeb0 100644 --- a/docs/tutorials/virtuals.md +++ b/docs/tutorials/virtuals.md @@ -18,22 +18,22 @@ want the email's domain. For example, the domain portion of 'test@gmail.com' is 'gmail.com'. Below is one way to implement the `domain` property using a virtual. -You define virtuals on a schema using the [`Schema#virtual()` function](/docs/api/schema.html#schema_Schema-virtual). +You define virtuals on a schema using the [`Schema#virtual()` function](../api/schema.html#schema_Schema-virtual). ```javascript [require:Virtuals.*basic] ``` -The `Schema#virtual()` function returns a [`VirtualType` object](/docs/api/virtualtype.html). Unlike normal document properties, +The `Schema#virtual()` function returns a [`VirtualType` object](../api/virtualtype.html). Unlike normal document properties, virtuals do not have any underlying value and Mongoose does not do any type coercion on virtuals. However, virtuals do have -[getters and setters](/docs/tutorials/getters-setters.html), which make +[getters and setters](getters-setters.html), which make them ideal for computed properties, like the `domain` example above. ## Virtual Setters You can also use virtuals to set multiple properties at once as an -alternative to [custom setters on normal properties](/docs/tutorials/getters-setters.html#setters). For example, suppose +alternative to [custom setters on normal properties](getters-setters.html#setters). For example, suppose you have two string properties: `firstName` and `lastName`. You can create a virtual property `fullName` that lets you set both of these properties at once. The key detail is that, in virtual getters and @@ -50,7 +50,7 @@ JSON. For example, if you pass a document to [Express' `res.json()` function](h virtuals will **not** be included by default. To include virtuals in `res.json()`, you need to set the -[`toJSON` schema option](/docs/guide.html#toJSON) to `{ virtuals: true }`. +[`toJSON` schema option](../guide.html#toJSON) to `{ virtuals: true }`. ```javascript [require:Virtuals.*toJSON] @@ -59,9 +59,9 @@ To include virtuals in `res.json()`, you need to set the ## Virtuals with Lean Virtuals are properties on Mongoose documents. If you use the -[lean option](/docs/tutorials/lean.html), that means your queries return POJOs +[lean option](lean.html), that means your queries return POJOs rather than full Mongoose documents. That means no virtuals if you use -[`lean()`](/docs/api/query.html#query_Query-lean). +[`lean()`](../api/query.html#query_Query-lean). ```javascript [require:Virtuals.*lean] @@ -82,11 +82,11 @@ based on Mongoose virtuals. ``` If you want to query by a computed property, you should set the property using -a [custom setter](/docs/tutorials/getters-setters.html) or [pre save middleware](/docs/middleware.html). +a [custom setter](getters-setters.html) or [pre save middleware](../middleware.html). ## Populate -Mongoose also supports [populating virtuals](/docs/populate.html). A populated +Mongoose also supports [populating virtuals](../populate.html). A populated virtual contains documents from another collection. To define a populated virtual, you need to specify: @@ -99,8 +99,8 @@ virtual, you need to specify: ## Further Reading -* [Virtuals in Mongoose Schemas](/docs/guide.html#virtuals) -* [Populate Virtuals](/docs/populate.html#populate-virtuals) +* [Virtuals in Mongoose Schemas](../guide.html#virtuals) +* [Populate Virtuals](../populate.html#populate-virtuals) * [Mongoose Lean Virtuals plugin](https://plugins.mongoosejs.io/plugins/lean-virtuals) * [Getting Started With Mongoose Virtuals](https://masteringjs.io/tutorials/mongoose/virtuals) -* [Understanding Virtuals in Mongoose](https://futurestud.io/tutorials/understanding-virtuals-in-mongoose) \ No newline at end of file +* [Understanding Virtuals in Mongoose](https://futurestud.io/tutorials/understanding-virtuals-in-mongoose) diff --git a/docs/typescript.md b/docs/typescript.md index 3149e67a207..09537839def 100644 --- a/docs/typescript.md +++ b/docs/typescript.md @@ -9,9 +9,9 @@ This guide describes Mongoose's recommended approach to working with Mongoose in To get started with Mongoose in TypeScript, you need to: 1. Create an interface representing a document in MongoDB. -2. Create a [Schema](/docs/guide.html) corresponding to the document interface. +2. Create a [Schema](guide.html) corresponding to the document interface. 3. Create a Model. -4. [Connect to MongoDB](/docs/connections.html). +4. [Connect to MongoDB](connections.html). ```typescript import { Schema, model, connect } from 'mongoose'; @@ -72,10 +72,10 @@ interface User extends Document { ``` This approach works, but we recommend your document interface _not_ extend `Document`. -Using `extends Document` makes it difficult for Mongoose to infer which properties are present on [query filters](/docs/queries.html), [lean documents](/docs/tutorials/lean.html), and other cases. +Using `extends Document` makes it difficult for Mongoose to infer which properties are present on [query filters](queries.html), [lean documents](tutorials/lean.html), and other cases. We recommend your document interface contain the properties defined in your schema and line up with what your documents look like in MongoDB. -Although you can add [instance methods](/docs/guide.html#methods) to your document interface, we do not recommend doing so. +Although you can add [instance methods](guide.html#methods) to your document interface, we do not recommend doing so. ### Using Custom Bindings @@ -90,4 +90,4 @@ However, before you do, please [open an issue on Mongoose's GitHub page](https:/ ### Next Up -Now that you've seen the basics of how to use Mongoose in TypeScript, let's take a look at [statics in TypeScript](/docs/typescript/statics.html). \ No newline at end of file +Now that you've seen the basics of how to use Mongoose in TypeScript, let's take a look at [statics in TypeScript](typescript/statics.html). diff --git a/docs/typescript/schemas.md b/docs/typescript/schemas.md index 87aeabf53b8..72f60121860 100644 --- a/docs/typescript/schemas.md +++ b/docs/typescript/schemas.md @@ -1,6 +1,6 @@ # Schemas in TypeScript -Mongoose [schemas](/docs/guide.html) are how you tell Mongoose what your documents look like. +Mongoose [schemas](../guide.html) are how you tell Mongoose what your documents look like. Mongoose schemas are separate from TypeScript interfaces, so you need to define both a _document interface_ and a _schema_. ```typescript @@ -86,4 +86,4 @@ const schema = new Schema, User>({ }); ``` -This is because Mongoose has numerous features that add paths to your schema, like [timestamps](https://masteringjs.io/tutorials/mongoose/timestamps), [plugins](/docs/plugins.html), etc. without you explicitly putting these paths in the `Schema()` constructor. \ No newline at end of file +This is because Mongoose has numerous features that add paths to your schema, like [timestamps](https://masteringjs.io/tutorials/mongoose/timestamps), [plugins](../plugins.html), etc. without you explicitly putting these paths in the `Schema()` constructor. diff --git a/docs/typescript/statics.md b/docs/typescript/statics.md index 6685acb91b1..31dce86f52e 100644 --- a/docs/typescript/statics.md +++ b/docs/typescript/statics.md @@ -1,6 +1,6 @@ # Statics in TypeScript -Mongoose [models](/docs/models.html) do **not** have an explicit generic parameter for [statics](/docs/guide.html#statics). +Mongoose [models](../models.html) do **not** have an explicit generic parameter for [statics](../guide.html#statics). If your model has statics, we recommend creating an interface that [extends](https://www.typescriptlang.org/docs/handbook/interfaces.html) Mongoose's `Model` interface as shown below. ```typescript @@ -22,4 +22,4 @@ schema.static('myStaticMethod', function myStaticMethod() { const User = model('User', schema); const answer: number = User.myStaticMethod(); // 42 -``` \ No newline at end of file +``` diff --git a/docs/validation.md b/docs/validation.md index c2dbffd1413..563498a85f9 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -48,7 +48,7 @@ Mongoose replaces `{VALUE}` with the value being validated. A common gotcha for beginners is that the `unique` option for schemas is *not* a validator. It's a convenient helper for building [MongoDB unique indexes](https://docs.mongodb.com/manual/core/index-unique/). -See the [FAQ](/docs/faq.html) for more information. +See the [FAQ](faq.html) for more information. ```javascript [require:The `unique` Option is Not a Validator] @@ -119,10 +119,10 @@ nested objects are not fully fledged paths. ### Update Validators In the above examples, you learned about document validation. Mongoose also -supports validation for [`update()`](/docs/api.html#query_Query-update), -[`updateOne()`](/docs/api.html#query_Query-updateOne), -[`updateMany()`](/docs/api.html#query_Query-updateMany), -and [`findOneAndUpdate()`](/docs/api.html#query_Query-findOneAndUpdate) operations. +supports validation for [`update()`](api.html#query_Query-update), +[`updateOne()`](api.html#query_Query-updateOne), +[`updateMany()`](api.html#query_Query-updateMany), +and [`findOneAndUpdate()`](api.html#query_Query-findOneAndUpdate) operations. Update validators are off by default - you need to specify the `runValidators` option.