Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Дубровин Алексей #15

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

Griboedoff
Copy link

No description provided.

@honest-hrundel honest-hrundel changed the title master Дубровин Алексей Apr 3, 2018
@honest-hrundel
Copy link

🍅 Пройдено тестов 8 из 10

@honest-hrundel
Copy link

🍅 Пройдено тестов 8 из 10

@honest-hrundel
Copy link

🍅 Пройдено тестов 9 из 10

@honest-hrundel
Copy link

🍅 Пройдено тестов 9 из 10

@honest-hrundel
Copy link

🍏 Пройдено тестов 10 из 10

// Ваша схема сувенира тут
_id: mongoose.Schema.Types.ObjectId,
tags: [String],
reviews: [mongoose.Schema.Types.Mixed],

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Всё таки для большей надёжности лучше определить схему Review, а в этой строке сделать reviews: [reviewSchema]

amount: Number,
country: { type: String, index: true },
rating: { type: Number, index: true },
isRecent: Boolean
});

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Было бы круто явным образом указать default и required для полей

}

getCheapSouvenirs(price) {
// Данный метод должен возвращать все сувениры, цена которых меньше или равна price
return this._Souvenir.find({ price: { $lte: price } });

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно немного симпатичнее this._Souvenir.where('price').lte(price), но это не замечание)

// ! Важно, чтобы метод работал очень быстро,
// поэтому учтите это при определении схем
return this._Souvenir.find({ country, rating: { $gte: rating }, price: { $lte: price } })
.count();
Copy link

@evgenymarkov evgenymarkov Apr 18, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай немного приберёмся здесь с форматированием, выглядит странно. Кстати, можно обойтись без find и сразу написать эти же параметры в count.

}

deleteOutOfStockSouvenirs() {
return this._Souvenir.find({ amount: { $eq: 0 } }).remove();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this._Souvenir.deleteMany({ amount: 0 }); несколько лаконичнее

$push: { reviews: review },
$set: { rating: ratingSum / reviewsCount }
});
// await

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

?

// Данный метод должен считать общую стоимость корзины пользователя login
// У пользователя может быть только одна корзина, поэтому это тоже можно отразить
// в схеме
const cart = ((await this._Cart.find({ login }, { items: 1, _id: 0 }))[0]).items;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

findOne


let sum = 0;
for (let orderedSouvenir of cart) {
const souvenir = (await this._Souvenir.find({ _id: orderedSouvenir.souvenirId }))[0];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Await в цикле это верный сигнал к тому, что стоит переписать кусок кода.
В большинстве случаев хочется получить N ресурсов и сделать что-то с ними независимо от порядка, тогда адекватнее применить Promise.all().
Но здесь есть второй нюанс – N обращений к БД в цикле. Этого можно и нужно избегать потому что всякая ODM/ORM да и голый SQL позволяют тебе сделать чуть более сложную выборку, но загрузить все нужные данные за 1 запрос.

@savichev-igor
Copy link
Contributor

🍪

@honest-hrundel
Copy link

🍏 Пройдено тестов 10 из 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

4 participants