Skip to content

Commit

Permalink
Merge pull request #13433 from Automattic/IslandRhythms/fix-callback-…
Browse files Browse the repository at this point in the history
…docs

docs: remove callback based examples
  • Loading branch information
vkarpov15 authored May 24, 2023
2 parents 2183b6c + 196c822 commit 0e08bb2
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 120 deletions.
33 changes: 11 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -208,17 +204,17 @@ 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
```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
Expand All @@ -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
Expand Down
8 changes: 5 additions & 3 deletions docs/connections.md
Original file line number Diff line number Diff line change
Expand Up @@ -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(function(error, result) { /* ... */ });
await MyModel.findOne();
```

That's because mongoose buffers model function calls internally. This
Expand All @@ -52,12 +52,14 @@ connecting.

```javascript
const MyModel = mongoose.model('Test', new Schema({ name: String }));
// Will just hang until mongoose successfully connects
MyModel.findOne(function(error, result) { /* ... */ });
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).
Expand Down
30 changes: 9 additions & 21 deletions docs/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,30 +41,22 @@ 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
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
Expand All @@ -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.
Expand All @@ -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
Expand All @@ -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
Expand Down
72 changes: 29 additions & 43 deletions docs/populate.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"
```

<h2 id="checking-populated"><a href="#checking-populated">Checking Whether a Field is Populated</a></h2>
Expand Down Expand Up @@ -192,26 +186,22 @@ 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);
```

<h2 id="populating-multiple-paths"><a href="#populating-multiple-paths">Populating Multiple Paths</a></h2>

What if we wanted to populate multiple paths at the same time?

```javascript
Story.
await Story.
find({ /* ... */ }).
populate('fans').
populate('author').
Expand All @@ -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' });
```

<h2 id="query-conditions"><a href="#query-conditions">Query conditions and other options</a></h2>
Expand All @@ -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',
Expand Down Expand Up @@ -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] }
]);
Expand Down Expand Up @@ -341,35 +331,31 @@ 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
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
Expand Down Expand Up @@ -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',
Expand Down
Loading

0 comments on commit 0e08bb2

Please # to comment.