|
@@ -27,14 +27,52 @@ class GoodsService extends CrudService {
|
|
|
return { filter, update };
|
|
|
}
|
|
|
|
|
|
- // 标签查询
|
|
|
- async beforeQuery(filter) {
|
|
|
- const { tags } = filter;
|
|
|
+ async query(filter, { skip = 0, limit, sort, desc, projection } = {}) {
|
|
|
+ // 处理排序
|
|
|
+ let condition = _.cloneDeep(filter);
|
|
|
+ condition = this.dealFilter(condition);
|
|
|
+ const pipeline = this.getQueryPipeline(condition);
|
|
|
+ if (parseInt(skip)) pipeline.push({ $skip: parseInt(skip) });
|
|
|
+ if (parseInt(limit)) pipeline.push({ $limit: parseInt(limit) });
|
|
|
+ const rs = await this.model.aggregate(pipeline);
|
|
|
+ return rs;
|
|
|
+ }
|
|
|
+
|
|
|
+ async count(filter) {
|
|
|
+ let condition = _.cloneDeep(filter);
|
|
|
+ condition = this.dealFilter(condition);
|
|
|
+ const pipeline = this.getQueryPipeline(condition);
|
|
|
+ pipeline.push({ $count: 'total' });
|
|
|
+ const total = await this.model.aggregate(pipeline);
|
|
|
+ return _.get(_.head(total), 'total', 0);
|
|
|
+ }
|
|
|
+
|
|
|
+ getQueryPipeline(filter) {
|
|
|
+ const pipeline = [];
|
|
|
+ const { tags, spec_name, ...others } = filter;
|
|
|
+ const $match = { ...others };
|
|
|
if (tags) {
|
|
|
- filter.tags = { $elemMatch: { $elemMatch: { $eq: tags } } };
|
|
|
+ $match.tags = { $elemMatch: { $elemMatch: { $eq: tags } } };
|
|
|
}
|
|
|
- return filter;
|
|
|
+ pipeline.push({ $match });
|
|
|
+ if (spec_name) {
|
|
|
+ const $addFields = { goods_id: { $toString: '$_id' } };
|
|
|
+ const $lookup = {
|
|
|
+ from: 'goodsSpec',
|
|
|
+ localField: 'goods_id',
|
|
|
+ foreignField: 'goods',
|
|
|
+ pipeline: [{ $match: { name: new RegExp(spec_name) } }],
|
|
|
+ as: 'sp',
|
|
|
+ };
|
|
|
+ const $unwind = '$sp';
|
|
|
+ const $project = { sp: 0, goods_id: 0 };
|
|
|
+ pipeline.push({ $addFields }, { $lookup }, { $unwind }, { $project });
|
|
|
+
|
|
|
+ }
|
|
|
+ pipeline.push({ $sort: { sort: -1 } });
|
|
|
+ return pipeline;
|
|
|
}
|
|
|
+
|
|
|
/**
|
|
|
* 检查商品编码是否唯一,若传id,则将该id排除在外
|
|
|
* @param {String} code 商品唯一编码
|