我有一个产品型号,价格可选。价格是可选的的原因是因为产品可能有变化,在这种情况下,价格以变化形式指定。问题是如何按照这样的逻辑编写产品按价格升序排序:如果产品有变化,则选择最低变化价格与其他产品进行比较,如果产品没有变化,则取产品的价格属性值进行比较与其他产品一起使用。
我的产品架构:
interface IProductVariation extends IMongooseId {
price: number;
//... some other properties
}
interface IProduct extends IMongooseId {
/* price is optional because in case of variations presence,
* prices will be specified in variations */
price?: number;
variations: IProductVariation[];
//...some other properties
}
const variationSchema = new Schema<IProductVariation>({
price: { type: Number, required: true },
// ...
});
const productSchema = new Schema<IProduct>({
price: Number,
variations: [variationSchema],
// ...
});
查询存储库中数据的方法(我需要正确的排序):
public async getPaginatedData(
page: number,
perPage: number,
query: FilterQuery<IProduct> = {},
sort?: FilterQuery<IProduct>
) {
return this.model
.find(query)
.limit(perPage)
.skip((page - 1) * perPage)
.sort(sort);
}
这样,如果存在变化,该方法将返回按最低变化价格排序的产品,否则按产品价格排序:
import { Aggregate, Model } from 'mongoose';
public async getPaginatedData(
page: number,
perPage: number,
query: FilterQuery<IProduct> = {},
sort?: FilterQuery<IProduct>
) {
const aggregatePipeline: any[] = [
{ $match: query },
{ $project: {
price: {
$cond: {
if: { $isArray: "$variations" },
then: { $min: "$variations.price" },
else: "$price"
}
},
// Include other fields if needed
}},
{ $sort: { price: 1 } }
];
const aggregation: Aggregate<IProduct[]> = this.model.aggregate(aggregatePipeline);
const totalCount: number = await this.model.countDocuments(query);
const result = await aggregation
.skip((page - 1) * perPage)
.limit(perPage)
.exec();
return { result, totalCount };
}