Skip to content

Commit

Permalink
Merge pull request #10633 from AbdelrahmanHafez/prefer-async-await
Browse files Browse the repository at this point in the history
get rid of co
  • Loading branch information
vkarpov15 committed Sep 1, 2021
2 parents 09dae52 + c4b0e86 commit 0e79c5c
Show file tree
Hide file tree
Showing 45 changed files with 8,433 additions and 9,237 deletions.
49 changes: 20 additions & 29 deletions examples/statics/statics.js
Expand Up @@ -9,34 +9,25 @@ require('./person.js')();
const Person = mongoose.model('Person');

// connect to a server to do a quick write / read example

mongoose.connect('mongodb://localhost/persons', function(err) {
if (err) {
throw err;
}

Person.create({ name: 'bill', age: 25, birthday: new Date().setFullYear((new Date().getFullYear() - 25)) },
function(err, bill) {
if (err) {
throw err;
}
console.log('People added to db: %s', bill.toString());

// using the static
Person.findPersonByName('bill', function(err, result) {
if (err) {
throw err;
}

console.log(result);
cleanup();
});
}
);
});

function cleanup() {
Person.remove(function() {
mongoose.disconnect();
run().catch(console.error);

async function run() {
await mongoose.connect('mongodb://localhost/persons');
const bill = await Person.create({
name: 'bill',
age: 25,
birthday: new Date().setFullYear((new Date().getFullYear() - 25))
});
console.log('People added to db: %s', bill.toString());

// using the static
const result = await Person.findPersonByName('bill');

console.log(result);
cleanup();
}

async function cleanup() {
await Person.remove();
mongoose.disconnect();
}
21 changes: 10 additions & 11 deletions lib/document.js
Expand Up @@ -2074,14 +2074,14 @@ Document.prototype.$isDefault = function(path) {
* Getter/setter, determines whether the document was removed or not.
*
* ####Example:
* product.remove(function (err, product) {
* product.$isDeleted(); // true
* product.remove(); // no-op, doesn't send anything to the db
* const product = await product.remove();
* product.$isDeleted(); // true
* product.remove(); // no-op, doesn't send anything to the db
*
* product.$isDeleted(false);
* product.$isDeleted(); // false
* product.remove(); // will execute a remove against the db
*
* product.$isDeleted(false);
* product.$isDeleted(); // false
* product.remove(); // will execute a remove against the db
* })
*
* @param {Boolean} [val] optional, overrides whether mongoose thinks the doc is deleted
* @return {Boolean} whether mongoose thinks this doc is deleted.
Expand Down Expand Up @@ -2161,10 +2161,9 @@ Document.prototype.isInit = function(path) {
*
* ####Example
*
* Thing.findOne().select('name').exec(function (err, doc) {
* doc.isSelected('name') // true
* doc.isSelected('age') // false
* })
* const doc = await Thing.findOne().select('name');
* doc.isSelected('name') // true
* doc.isSelected('age') // false
*
* @param {String|Array<String>} path
* @return {Boolean}
Expand Down
31 changes: 12 additions & 19 deletions lib/model.js
Expand Up @@ -2327,10 +2327,8 @@ Model.countDocuments = function countDocuments(conditions, options, callback) {
*
* ####Example:
*
* Adventure.count({ type: 'jungle' }, function (err, count) {
* if (err) ..
* console.log('there are %d jungle adventures', count);
* });
* const count = await Adventure.count({ type: 'jungle' });
* console.log('there are %d jungle adventures', count);
*
* @deprecated
* @param {Object} filter
Expand Down Expand Up @@ -2494,11 +2492,9 @@ Model.$where = function $where() {
* If you need full-fledged validation, use the traditional approach of first
* retrieving the document.
*
* Model.findById(id, function (err, doc) {
* if (err) ..
* doc.name = 'jason bourne';
* doc.save(callback);
* });
* const doc = await Model.findById(id);
* doc.name = 'jason bourne';
* await doc.save();
*
* @param {Object} [conditions]
* @param {Object} [update]
Expand Down Expand Up @@ -4104,22 +4100,19 @@ Model.mapReduce = function mapReduce(o, callback) {
* ####Example:
*
* // Find the max balance of all accounts
* Users.aggregate([
* const res = await Users.aggregate([
* { $group: { _id: null, maxBalance: { $max: '$balance' }}},
* { $project: { _id: 0, maxBalance: 1 }}
* ]).
* then(function (res) {
* console.log(res); // [ { maxBalance: 98000 } ]
* });
* ]);
*
* console.log(res); // [ { maxBalance: 98000 } ]
*
* // Or use the aggregation pipeline builder.
* Users.aggregate().
* const res = await Users.aggregate().
* group({ _id: null, maxBalance: { $max: '$balance' } }).
* project('-id maxBalance').
* exec(function (err, res) {
* if (err) return handleError(err);
* console.log(res); // [ { maxBalance: 98 } ]
* });
* exec();
* console.log(res); // [ { maxBalance: 98 } ]
*
* ####NOTE:
*
Expand Down
19 changes: 7 additions & 12 deletions lib/query.js
Expand Up @@ -605,12 +605,9 @@ Query.prototype._validateOp = function() {
*
* ####Example
*
* MyModel.where('tags').size(0).exec(function (err, docs) {
* if (err) return handleError(err);
*
* assert(Array.isArray(docs));
* console.log('documents with 0 tags', docs);
* })
* const docs = await MyModel.where('tags').size(0).exec();
* assert(Array.isArray(docs));
* console.log('documents with 0 tags', docs);
*
* @see $size http://docs.mongodb.org/manual/reference/operator/size/
* @method size
Expand Down Expand Up @@ -5080,12 +5077,10 @@ Query.prototype._applyPaths = function applyPaths() {
* // Because `.next()` returns a promise, you can use co
* // to easily iterate through all documents without loading them
* // all into memory.
* co(function*() {
* const cursor = Thing.find({ name: /^hello/ }).cursor();
* for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) {
* console.log(doc);
* }
* });
* const cursor = Thing.find({ name: /^hello/ }).cursor();
* for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
* console.log(doc);
* }
*
* ####Valid options
*
Expand Down
39 changes: 18 additions & 21 deletions package.json
Expand Up @@ -42,7 +42,6 @@
"bluebird": "3.5.5",
"chalk": "2.4.2",
"cheerio": "1.0.0-rc.2",
"co": "4.6.0",
"dox": "0.3.1",
"eslint": "7.1.0",
"eslint-plugin-mocha-no-only": "1.1.0",
Expand Down Expand Up @@ -105,26 +104,24 @@
"extends": [
"eslint:recommended"
],
"overrides": [
{
"files": [
"**/*.{ts,tsx}"
],
"extends": [
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"plugins": [
"@typescript-eslint"
],
"rules": {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/explicit-module-boundary-types": "off"
}
"overrides": [{
"files": [
"**/*.{ts,tsx}"
],
"extends": [
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"plugins": [
"@typescript-eslint"
],
"rules": {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/explicit-module-boundary-types": "off"
}
],
}],
"plugins": [
"mocha-no-only"
],
Expand Down Expand Up @@ -248,4 +245,4 @@
"type": "opencollective",
"url": "https://opencollective.com/mongoose"
}
}
}
53 changes: 22 additions & 31 deletions test/aggregate.test.js
Expand Up @@ -7,7 +7,6 @@
const start = require('./common');

const assert = require('assert');
const co = require('co');

const Aggregate = require('../lib/aggregate');

Expand Down Expand Up @@ -928,7 +927,7 @@ describe('aggregate: ', function() {
});
});

it('setting option in pre (gh-7606)', function() {
it('setting option in pre (gh-7606)', async function() {
const s = new Schema({ name: String });

s.pre('aggregate', function(next) {
Expand All @@ -938,17 +937,15 @@ describe('aggregate: ', function() {

const M = db.model('Test', s);

return co(function*() {
yield M.create([{ name: 'alpha' }, { name: 'Zeta' }]);
await M.create([{ name: 'alpha' }, { name: 'Zeta' }]);

const docs = yield M.aggregate([{ $sort: { name: 1 } }]);
const docs = await M.aggregate([{ $sort: { name: 1 } }]);

assert.equal(docs[0].name, 'alpha');
assert.equal(docs[1].name, 'Zeta');
});
assert.equal(docs[0].name, 'alpha');
assert.equal(docs[1].name, 'Zeta');
});

it('adding to pipeline in pre (gh-8017)', function() {
it('adding to pipeline in pre (gh-8017)', async function() {
const s = new Schema({ name: String });

s.pre('aggregate', function(next) {
Expand All @@ -958,14 +955,12 @@ describe('aggregate: ', function() {

const M = db.model('Test', s);

return co(function*() {
yield M.create([{ name: 'alpha' }, { name: 'Zeta' }]);
await M.create([{ name: 'alpha' }, { name: 'Zeta' }]);

const docs = yield M.aggregate([{ $sort: { name: 1 } }]);
const docs = await M.aggregate([{ $sort: { name: 1 } }]);

assert.equal(docs.length, 1);
assert.equal(docs[0].name, 'Zeta');
});
assert.equal(docs.length, 1);
assert.equal(docs[0].name, 'Zeta');
});

it('post', function(done) {
Expand Down Expand Up @@ -1102,30 +1097,26 @@ describe('aggregate: ', function() {
});
});

it('cursor (gh-3160)', function() {
it('cursor (gh-3160)', async function() {
const MyModel = db.model('Test', { name: String });

return co(function * () {
yield MyModel.create({ name: 'test' });
await MyModel.create({ name: 'test' });

const cursor = MyModel.
aggregate([{ $match: { name: 'test' } }, { $project: { name: '$name' } }]).
allowDiskUse(true).
cursor({ batchSize: 2500 });
const cursor = MyModel.
aggregate([{ $match: { name: 'test' } }, { $project: { name: '$name' } }]).
allowDiskUse(true).
cursor({ batchSize: 2500 });

assert.ok(cursor.eachAsync);
});
assert.ok(cursor.eachAsync);
});

it('catch() (gh-7267)', function() {
it('catch() (gh-7267)', async function() {
const MyModel = db.model('Test', {});

return co(function * () {
const err = yield MyModel.aggregate([{ $group: { foo: 'bar' } }]).
catch(err => err);
assert.ok(err instanceof Error);
assert.equal(err.name, 'MongoServerError');
});
const err = await MyModel.aggregate([{ $group: { foo: 'bar' } }])
.then(() => null, err => err);
assert.ok(err instanceof Error);
assert.equal(err.name, 'MongoServerError');
});

it('cursor() without options (gh-3855)', function(done) {
Expand Down

0 comments on commit 0e79c5c

Please sign in to comment.