image.png

2表查询

image.png

  1. const user_Schema = require("../model/user_Schema");//(第1个表)
  2. const role_Schema = require("../model/role_Schema");//(第2个表)
  3. const user_role_Schema = require("../model/t_user_role_Schema");
  4. router.get('/',async(req,res)=>{
  5. let result=await user_Schema.aggregate([
  6. {
  7. $lookup:
  8. {
  9. from: "role", //关联第二张表(角色)
  10. localField: "pid",//user表的主键id (第1个表)
  11. foreignField: "id_name_", //role角色 表 主键ID的字段 (第2个表role)
  12. as: "items"
  13. }
  14. }
  15. ])
  16. console.log(result);
  17. res.send(result)
  18. })

image.png

3表查询

  1. router.get('/',async(req,res)=>{
  2. let result=await user_Schema.aggregate([
  3. {
  4. lookup:
  5. {
  6. from: "t_user_role", //关联第二张表(角色)
  7. localField: "pidxxx",//user表的主键id (第1个表)
  8. foreignField: "id_namexxxx_", //role角色 表 主键ID的字段 (第2个表role)
  9. as: "items"
  10. }
  11. }
  12. ])
  13. console.log(result);
  14. res.send(result)
  15. })
  16. module.exports=router;

4表查询之条件

  1. router.get('/',async(req,res)=>{
  2. let result=await user_Schema.aggregate([
  3. {
  4. match:{id_name:1}
  5. }
  6. ])
  7. console.log(result);
  8. res.send(result)
  9. })
  10. module.exports=router;
  1. [{"id":"60b0bc4c74d0832de80b8db2","id_name":1,"username":"陈陈","pid":1,"uid":1,"items":[{"id":"60b0a41e898fd52f8c99dc75","role_name":"管理员","id_name_":1}]}]