Skip to content

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

Open
Griboedoff wants to merge 5 commits into
urfu-2017:masterfrom
Griboedoff:master
Open

Дубровин Алексей#15
Griboedoff wants to merge 5 commits into
urfu-2017:masterfrom
Griboedoff:master

Conversation

@Griboedoff
Copy link
Copy Markdown

No description provided.

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

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

@honest-hrundel
Copy link
Copy Markdown

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

@honest-hrundel
Copy link
Copy Markdown

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

@honest-hrundel
Copy link
Copy Markdown

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

@honest-hrundel
Copy link
Copy Markdown

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

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

Choose a reason for hiding this comment

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

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

Comment thread queries.js
country: { type: String, index: true },
rating: { type: Number, index: true },
isRecent: Boolean
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread queries.js

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

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), но это не замечание)

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

@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.

Comment thread queries.js
}

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

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 }); несколько лаконичнее

Comment thread queries.js
$push: { reviews: review },
$set: { rating: ratingSum / reviewsCount }
});
// await
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

?

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

Choose a reason for hiding this comment

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

findOne

Comment thread queries.js

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

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
Copy Markdown
Contributor

🍪

@honest-hrundel
Copy link
Copy Markdown

🍏 Пройдено тестов 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