接着上次的讲解
通过接口进行添加数据
router.get('/test',function(req,res){
Category.insertMany([
{
"category_id":"001",
"category":"String",
"name":"学历"
},
{
"category_id":"002",
"category":"String",
"name":"新进员工工作经验"
}
])
Grade.insertMany([
{
"grade_id":"g_001",
"category_id":"001",
"name":"本科"
},
{
"grade_id":"g_002",
"category_id":"002",
"name":"博士"
}
])
Level.insertMany([
{
"grade_id":"g_001",
"level_id":"l_001",
"name":"985、211院校"
},
{
"grade_id":"g_002",
"level_id":"l_002",
"name":"一本院校、一本专业"
}
])
})
集合创建好了,接下来写一些操作。
router.get("/getCategoryAccount", (req, res) => {
Category.find({})
.then(category => {
res.json(category);
})
.catch(err => {
console.log(err);
res.json(err);
});
});
⭐️⭐️⭐️⭐️ $lookup
的功能及用法
是将每个输入待处理的文档,经过$lookup 阶段的处理,输出的新文档中会包含一个新生成的数组列(户名可根据需要命名新key的名字 )。数组列存放的数据 是 来自 被Join 集合的适配文档,如果没有,集合为空(即 为[ ])
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
- from: “要连接的表”,
- localField: “当前Collection中需要连接的字段”,
- foreignField: “外连Collection中连接查询的字段”,
- as: "把获取到的的值赋值给这个字段
router.get("/getGradeBycateGory",function(req,res){
Category.aggregate([{
$lookup:{
from:"grades",
localField:"category_id",
foreignField:"category_id",
as:"item"
}
}],function(err,data){
if(err){
console.log(err);
return;
}
res.json({
status: '200',
result:data,
})
console.log(JSON.stringify(data))
})
})
router.get("/getGradeBycateGory_list",function(req,res){
console.log(req.query)
let category_name = req.query.name;
console.log(category_name)
Category.aggregate([{
$lookup:{
from:"grades",
localField:"category_id",
foreignField:"category_id",
as:"item_grade"
}
},{
$match: {
"name": category_name
}
}],function(err,data){
if(err){
console.log(err);
return;
}
res.json({
status: '200',
result:data,
})
console.log(JSON.stringify(data))
})
})
router.get("/getLevelByCategoryGrade",function(req,res){
Grade.aggregate([{
$lookup:{
from:"categorys",
localField:"category_id",
foreignField:"category_id",
as:"item_grade"
}
},
{
$lookup:{
from:"levels",
localField:"grade_id",
foreignField:"grade_id",
as:"item_level"
}
}],function(err,data){
if(err){
console.log(err);
return;
}
res.json({
status: '200',
result:data,
})
console.log(JSON.stringify(data))
})
})
router.get("/getLevelByCategoryGrade_list",function(req,res){
console.log(req.query);
let category_id = req.query.category_id;
let grade_id =req.query.grade_id;
Grade.aggregate([{
$lookup:{
from:"categorys",
localField:"category_id",
foreignField:"category_id",
as:"item_grade"
}
},{
$match: {
"category_id": category_id
}
},
{
$lookup:{
from:"levels",
localField:"grade_id",
foreignField:"grade_id",
as:"item_level"
}
},{
$match: {
"grade_id": grade_id
}
}],function(err,data){
if(err){
console.log(err);
return;
}
res.json({
status: '200',
result:data,
})
console.log(JSON.stringify(data))
})
})