problem description
< H2 > how does mongoose jointly check and complete the data and then classify and aggregate according to the fields of the joint search? < / H2 >
I now have two tables: a product table Product
, a product category table Category
, a product table option
associated category table,
Product Table
const mongoose = require("../index")
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId
const newSchema = new Schema({
name:String,
dec:String,
tags:Array,
originalPrice:Number,
presentPrice:Number,
proImg:Array,
detailImg:Array,
option:{
type:ObjectId,
ref:"Category"
},
})
module.exports = mongoose.model("Product",newSchema,"product")
Category Table
const mongoose = require("../index")
const Schema = mongoose.Schema;
const newSchema = new Schema({
name:String,
isShow:{
type:Boolean,
default:true,
},
})
module.exports = mongoose.model("Category",newSchema,"category")
General joint search const data = await dbProduct.find (). Populate ("option")
router.get("/homeLists/index", async ctx => {
// 201871517:38:12
// const lists = await dbProduct.aggregate().group({_id:"$option"}).count("productNumber")
// console.log("lists :", lists);
const categoryLists = await dbCategory.find()
const productLists = await dbProduct.find()
let tempList = []
categoryLists.forEach(cItem => { //
let categoryInfo = {
title: cItem.name,
subTitle: "Fashion Make-up", //
list: []
}
productLists.forEach(pItem => {
if (pItem.option.toString() == cItem._id.toString()) { //_id _id
console.log("true :", true);
let productInfo = {
productName: pItem.name,
proDec: pItem.dec,
img: pItem.proImg[0]
}
categoryInfo.list.push(productInfo)
}
});
tempList.push(categoryInfo) //
})
ctx.body = tempList
})
I hope to use the aggregation function of mongoose to achieve it at one time!