From 6ef8878996a0118375e5bbdaaba0d145ade36d88 Mon Sep 17 00:00:00 2001 From: Daniel Diaz <39510674+IslandRhythms@users.noreply.github.com> Date: Wed, 24 May 2023 11:44:06 -0400 Subject: [PATCH 1/4] docs: remove callback based examples --- README.md | 33 +++++++-------------- docs/connections.md | 6 ++-- docs/models.md | 30 ++++++------------- docs/populate.md | 72 ++++++++++++++++++--------------------------- docs/queries.md | 37 ++++++++--------------- docs/schematypes.md | 11 ++++--- 6 files changed, 70 insertions(+), 119 deletions(-) diff --git a/README.md b/README.md index e911e814ba3..bc4dc5f138a 100644 --- a/README.md +++ b/README.md @@ -181,17 +181,13 @@ Once we have our model, we can then instantiate it, and save it: ```js const instance = new MyModel(); instance.my.key = 'hello'; -instance.save(function(err) { - // -}); +await instance.save(); ``` Or we can find documents from the same collection ```js -MyModel.find({}, function(err, docs) { - // docs.forEach -}); +await MyModel.find({}); ``` You can also `findOne`, `findById`, `update`, etc. @@ -208,8 +204,8 @@ For more details check out [the docs](http://mongoosejs.com/docs/queries.html). ```js const conn = mongoose.createConnection('your connection string'); const MyModel = conn.model('ModelName', schema); -const m = new MyModel; -m.save(); // works +const m = new MyModel(); +await m.save(); // works ``` vs @@ -217,8 +213,8 @@ vs ```js const conn = mongoose.createConnection('your connection string'); const MyModel = mongoose.model('ModelName', schema); -const m = new MyModel; -m.save(); // does not work b/c the default connection object was never connected +const m = new MyModel(); +await m.save(); // does not work b/c the default connection object was never connected ``` ### Embedded Documents @@ -241,25 +237,18 @@ const post = new BlogPost(); // create a comment post.comments.push({ title: 'My comment' }); -post.save(function(err) { - if (!err) console.log('Success!'); -}); +await post.save(); ``` The same goes for removing them: ```js -BlogPost.findById(myId, function(err, post) { - if (!err) { - post.comments[0].remove(); - post.save(function(err) { - // do something - }); - } -}); +const post = await BlogPost.findById(myId); +post.comments[0].deleteOne(); +await post.save(); ``` -Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the `save()` error callback, so error handling is a snap! +Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. ### Middleware diff --git a/docs/connections.md b/docs/connections.md index ab7b588ed3d..b17bda2bffe 100644 --- a/docs/connections.md +++ b/docs/connections.md @@ -39,10 +39,10 @@ Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB. ```javascript -mongoose.connect('mongodb://127.0.0.1:27017/myapp'); +await mongoose.connect('mongodb://127.0.0.1:27017/myapp'); const MyModel = mongoose.model('Test', new Schema({ name: String })); // Works -MyModel.findOne(function(error, result) { /* ... */ }); +await MyModel.findOne(); ``` That's because mongoose buffers model function calls internally. This @@ -53,7 +53,7 @@ connecting. ```javascript const MyModel = mongoose.model('Test', new Schema({ name: String })); // Will just hang until mongoose successfully connects -MyModel.findOne(function(error, result) { /* ... */ }); +await MyModel.findOne(); setTimeout(function() { mongoose.connect('mongodb://127.0.0.1:27017/myapp'); diff --git a/docs/models.md b/docs/models.md index 200556b96c2..f32104a6b9e 100644 --- a/docs/models.md +++ b/docs/models.md @@ -41,22 +41,14 @@ them and saving to the database is easy. const Tank = mongoose.model('Tank', yourSchema); const small = new Tank({ size: 'small' }); -small.save(function(err) { - if (err) return handleError(err); - // saved! -}); +await small.save(); // or -Tank.create({ size: 'small' }, function(err, small) { - if (err) return handleError(err); - // saved! -}); +await Tank.create({ size: 'small' }); // or, for inserting large batches of documents -Tank.insertMany([{ size: 'small' }], function(err) { - -}); +await Tank.insertMany([{ size: 'small' }]); ``` Note that no tanks will be created/removed until the connection your model @@ -64,7 +56,7 @@ uses is open. Every model has an associated connection. When you use `mongoose.model()`, your model will use the default mongoose connection. ```javascript -mongoose.connect('mongodb://127.0.0.1/gettingstarted'); +await mongoose.connect('mongodb://127.0.0.1/gettingstarted'); ``` If you create a custom connection, use that connection's `model()` function @@ -80,7 +72,7 @@ Finding documents is easy with Mongoose, which supports the [rich](https://www.m Documents can be retrieved using a `model`'s [find](api/model.html#model_Model-find), [findById](api/model.html#model_Model-findById), [findOne](api/model.html#model_Model-findOne), or [where](api/model.html#model_Model-where) static functions. ```javascript -Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(callback); +await Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(); ``` See the chapter on [queries](queries.html) for more details on how to use the [Query](api/query.html) api. @@ -91,10 +83,7 @@ Models have static `deleteOne()` and `deleteMany()` functions for removing all documents matching the given `filter`. ```javascript -Tank.deleteOne({ size: 'large' }, function(err) { - if (err) return handleError(err); - // deleted at most one tank document -}); +await Tank.deleteOne({ size: 'large' }); ``` ## Updating @@ -104,10 +93,9 @@ database without returning them to your application. See the [API](api/model.html#model_Model-updateOne) docs for more detail. ```javascript -Tank.updateOne({ size: 'large' }, { name: 'T-90' }, function(err, res) { - // Updated at most one doc, `res.nModified` contains the number - // of docs that MongoDB updated -}); +// Updated at most one doc, `res.nModified` contains the number +// of docs that MongoDB updated +await Tank.updateOne({ size: 'large' }, { name: 'T-90' }); ``` _If you want to update a single document in the db and return it to your diff --git a/docs/populate.md b/docs/populate.md index a850383688a..58226e65130 100644 --- a/docs/populate.md +++ b/docs/populate.md @@ -94,14 +94,12 @@ So far we haven't done anything much different. We've merely created a `author` using the query builder: ```javascript -Story. +const story = await Story. findOne({ title: 'Casino Royale' }). populate('author'). - exec(function(err, story) { - if (err) return handleError(err); - console.log('The author is %s', story.author.name); - // prints "The author is Ian Fleming" - }); + exec(); +// prints "The author is Ian Fleming" +console.log('The author is %s', story.author.name); ``` Populated paths are no longer set to their original `_id` , their value @@ -118,13 +116,9 @@ You can manually populate a property by setting it to a document. The document must be an instance of the model your `ref` property refers to. ```javascript -Story.findOne({ title: 'Casino Royale' }, function(error, story) { - if (error) { - return handleError(error); - } - story.author = author; - console.log(story.author.name); // prints "Ian Fleming" -}); +const story = await Story.findOne({ title: 'Casino Royale' }); +story.author = author; +console.log(story.author.name); // prints "Ian Fleming" ```

Checking Whether a Field is Populated

@@ -192,18 +186,14 @@ documents? This can be accomplished by passing the usual to the populate method: ```javascript -Story. +const story = await Story. findOne({ title: /casino royale/i }). - populate('author', 'name'). // only return the Persons name - exec(function(err, story) { - if (err) return handleError(err); - - console.log('The author is %s', story.author.name); - // prints "The author is Ian Fleming" - - console.log('The authors age is %s', story.author.age); - // prints "The authors age is null" - }); + populate('author', 'name'). + exec(); // only return the Persons name +// prints "The author is Ian Fleming" +console.log('The author is %s', story.author.name); +// prints "The authors age is null" +console.log('The authors age is %s', story.author.age); ```

Populating Multiple Paths

@@ -211,7 +201,7 @@ Story. What if we wanted to populate multiple paths at the same time? ```javascript -Story. +await Story. find({ /* ... */ }). populate('fans'). populate('author'). @@ -224,12 +214,12 @@ one will take effect. ```javascript // The 2nd `populate()` call below overwrites the first because they // both populate 'fans'. -Story. +await Story. find(). populate({ path: 'fans', select: 'name' }). populate({ path: 'fans', select: 'email' }); // The above is equivalent to: -Story.find().populate({ path: 'fans', select: 'email' }); +await Story.find().populate({ path: 'fans', select: 'email' }); ```

Query conditions and other options

@@ -238,7 +228,7 @@ What if we wanted to populate our fans array based on their age and select just their names? ```javascript -Story. +await Story. find(). populate({ path: 'fans', @@ -283,7 +273,7 @@ does **not** limit on a per-document basis for backwards compatibility. For exam suppose you have 2 stories: ```javascript -Story.create([ +await Story.create([ { title: 'Casino Royale', fans: [1, 2, 3, 4, 5, 6, 7, 8] }, { title: 'Live and Let Die', fans: [9, 10] } ]); @@ -341,22 +331,20 @@ But, if you have a good reason to want an array of child pointers, you can `push()` documents onto the array as shown below. ```javascript -story1.save(); +await story1.save(); author.stories.push(story1); -author.save(callback); +await author.save(); ``` This allows us to perform a `find` and `populate` combo: ```javascript -Person. +const person = await Person. findOne({ name: 'Ian Fleming' }). - populate('stories'). // only works if we pushed refs to children - exec(function(err, person) { - if (err) return handleError(err); - console.log(person); - }); + populate('stories'). + exec(); // only works if we pushed refs to children +console.log(person); ``` It is debatable that we really want two sets of pointers as they may get @@ -364,12 +352,10 @@ out of sync. Instead we could skip populating and directly `find()` the stories we are interested in. ```javascript -Story. +const stories = await Story. find({ author: author._id }). - exec(function(err, stories) { - if (err) return handleError(err); - console.log('The stories are an array: ', stories); - }); + exec(); +console.log('The stories are an array: ', stories); ``` The documents returned from @@ -430,7 +416,7 @@ wanted a user's friends of friends? Specify the `populate` option to tell mongoose to populate the `friends` array of all the user's friends: ```javascript -User. +await User. findOne({ name: 'Val' }). populate({ path: 'friends', diff --git a/docs/queries.md b/docs/queries.md index 9b7ffc160a9..15bc45317fb 100644 --- a/docs/queries.md +++ b/docs/queries.md @@ -37,29 +37,21 @@ A query also has a `.then()` function, and thus can be used as a promise. ## Executing -When executing a query with a `callback` function, you specify your query as a JSON document. The JSON document's syntax is the same as the [MongoDB shell](http://www.mongodb.com/docs/manual/tutorial/query-documents/). +When executing a query, you specify your query as a JSON document. The JSON document's syntax is the same as the [MongoDB shell](http://www.mongodb.com/docs/manual/tutorial/query-documents/). ```javascript const Person = mongoose.model('Person', yourSchema); // find each person with a last name matching 'Ghost', selecting the `name` and `occupation` fields -Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function(err, person) { - if (err) return handleError(err); - // Prints "Space Ghost is a talk show host". - console.log('%s %s is a %s.', person.name.first, person.name.last, - person.occupation); -}); +const person = await Person.findOne({ 'name.last': 'Ghost' }, 'name occupation'); +// Prints "Space Ghost is a talk show host". +console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation); ``` -Mongoose executed the query and passed the results to `callback`. All callbacks in Mongoose use the pattern: -`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/model.html#model_Model-findOne), `find()` a [list of documents](api/model.html#model_Model-find), `count()` [the number of documents](api/model.html#model_Model-count), `update()` the [number of documents affected](api/model.html#model_Model-update), etc. -The [API docs for Models](api/model.html) provide more detail on what is passed to the callbacks. +What `person` is depends on the operation: For `findOne()` it is a [potentially-null single document](api/model.html#model_Model-findOne), `find()` a [list of documents](api/model.html#model_Model-find), `count()` [the number of documents](api/model.html#model_Model-count), `update()` the [number of documents affected](api/model.html#model_Model-update), etc. +The [API docs for Models](api/model.html) provide more details. -Now let's look at what happens when no `callback` is passed: +Now let's look at what happens when no `await` is used: ```javascript // find each person with a last name matching 'Ghost' @@ -69,12 +61,9 @@ const query = Person.findOne({ 'name.last': 'Ghost' }); query.select('name occupation'); // execute the query at a later time -query.exec(function(err, person) { - if (err) return handleError(err); - // Prints "Space Ghost is a talk show host." - console.log('%s %s is a %s.', person.name.first, person.name.last, - person.occupation); -}); +const person = query.exec(); + // Prints "Space Ghost is a talk show host." +console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation); ``` In the above code, the `query` variable is of type [Query](api/query.html). @@ -83,7 +72,7 @@ The below 2 examples are equivalent. ```javascript // With a JSON doc -Person. +await Person. find({ occupation: /host/, 'name.last': 'Ghost', @@ -93,7 +82,7 @@ Person. limit(10). sort({ occupation: -1 }). select({ name: 1, occupation: 1 }). - exec(callback); + exec(); // Using query builder Person. @@ -104,7 +93,7 @@ Person. limit(10). sort('-occupation'). select('name occupation'). - exec(callback); + exec(); ``` A full list of [Query helper functions can be found in the API docs](api/query.html). diff --git a/docs/schematypes.md b/docs/schematypes.md index 37525c969b6..b31bdd8f0b8 100644 --- a/docs/schematypes.md +++ b/docs/schematypes.md @@ -343,13 +343,12 @@ will all result in a [CastError](validation.html#cast-errors) once validated, me ```javascript const Assignment = mongoose.model('Assignment', { dueDate: Date }); -Assignment.findOne(function(err, doc) { - doc.dueDate.setMonth(3); - doc.save(callback); // THIS DOES NOT SAVE YOUR CHANGE +const doc = await Assignment.findOne(); +doc.dueDate.setMonth(3); +await doc.save(); // THIS DOES NOT SAVE YOUR CHANGE - doc.markModified('dueDate'); - doc.save(callback); // works -}); +doc.markModified('dueDate'); +await doc.save(); // works ```

Buffer

From 3f53facb19c542530d526880500167f348a3736f Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Wed, 24 May 2023 11:57:15 -0400 Subject: [PATCH 2/4] Update docs/queries.md Co-authored-by: hasezoey --- docs/queries.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/queries.md b/docs/queries.md index 15bc45317fb..a87d4916d24 100644 --- a/docs/queries.md +++ b/docs/queries.md @@ -61,7 +61,7 @@ const query = Person.findOne({ 'name.last': 'Ghost' }); query.select('name occupation'); // execute the query at a later time -const person = query.exec(); +const person = await query.exec(); // Prints "Space Ghost is a talk show host." console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation); ``` From 45a2c29c17a77614c7dea4a452f9923cfef23607 Mon Sep 17 00:00:00 2001 From: Daniel Diaz <39510674+IslandRhythms@users.noreply.github.com> Date: Wed, 24 May 2023 14:37:52 -0400 Subject: [PATCH 3/4] made requested changes --- docs/connections.md | 6 +++--- docs/queries.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/connections.md b/docs/connections.md index b17bda2bffe..8f9c29ecf7f 100644 --- a/docs/connections.md +++ b/docs/connections.md @@ -39,10 +39,10 @@ Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB. ```javascript -await mongoose.connect('mongodb://127.0.0.1:27017/myapp'); +mongoose.connect('mongodb://127.0.0.1:27017/myapp'); const MyModel = mongoose.model('Test', new Schema({ name: String })); // Works -await MyModel.findOne(); +MyModel.findOne(); ``` That's because mongoose buffers model function calls internally. This @@ -53,7 +53,7 @@ connecting. ```javascript const MyModel = mongoose.model('Test', new Schema({ name: String })); // Will just hang until mongoose successfully connects -await MyModel.findOne(); +MyModel.findOne(); setTimeout(function() { mongoose.connect('mongodb://127.0.0.1:27017/myapp'); diff --git a/docs/queries.md b/docs/queries.md index a87d4916d24..2476a50efa6 100644 --- a/docs/queries.md +++ b/docs/queries.md @@ -85,7 +85,7 @@ await Person. exec(); // Using query builder -Person. +await Person. find({ occupation: /host/ }). where('name.last').equals('Ghost'). where('age').gt(17).lt(66). From 196c8224710d919cedabebfdce74857b2143a471 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Wed, 24 May 2023 14:50:04 -0400 Subject: [PATCH 4/4] Update connections.md --- docs/connections.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/connections.md b/docs/connections.md index 8f9c29ecf7f..2e28b041598 100644 --- a/docs/connections.md +++ b/docs/connections.md @@ -42,7 +42,7 @@ mongoose to establish a connection to MongoDB. mongoose.connect('mongodb://127.0.0.1:27017/myapp'); const MyModel = mongoose.model('Test', new Schema({ name: String })); // Works -MyModel.findOne(); +await MyModel.findOne(); ``` That's because mongoose buffers model function calls internally. This @@ -52,12 +52,14 @@ connecting. ```javascript const MyModel = mongoose.model('Test', new Schema({ name: String })); -// Will just hang until mongoose successfully connects -MyModel.findOne(); +const promise = MyModel.findOne(); setTimeout(function() { mongoose.connect('mongodb://127.0.0.1:27017/myapp'); }, 60000); + +// Will just hang until mongoose successfully connects +await promise; ``` To disable buffering, turn off the [`bufferCommands` option on your schema](guide.html#bufferCommands).