-
Notifications
You must be signed in to change notification settings - Fork 40
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
base: master
Are you sure you want to change the base?
Дубровин Алексей #15
Conversation
🍅 Пройдено тестов 8 из 10 |
🍅 Пройдено тестов 8 из 10 |
🍅 Пройдено тестов 9 из 10 |
🍅 Пройдено тестов 9 из 10 |
🍏 Пройдено тестов 10 из 10 |
// Ваша схема сувенира тут | ||
_id: mongoose.Schema.Types.ObjectId, | ||
tags: [String], | ||
reviews: [mongoose.Schema.Types.Mixed], |
There was a problem hiding this comment.
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 | ||
}); |
There was a problem hiding this comment.
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 } }); |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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]; |
There was a problem hiding this comment.
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 запрос.
🍪 |
🍏 Пройдено тестов 10 из 10 |
No description provided.