Aggregate 关联查询

定义文档结构

分类表

// 连接数据库
const mongoose = require('mongoose')

// eggadmin 用户名
// 123456 密码
// 127.0.0.1:27017 服务器及端口
// eggcms 数据库
mongoose.connect('mongodb://eggadmin:123456@127.0.0.1:27017/eggcms', function (err, data) {
  if (err) {
    console.log(err, '数据库连接成功')
    return;
  }
  console.log('数据库连接成功')
})

module.exports = mongoose

文章表

const mongoose = require('./db')

// 文章表结构
const ArticleSchema = new mongoose.Schema({
  title: {
    type: String,
    unique: true
  },
  cid: { // 文章分类id
    type: mongoose.Schema.Types.ObjectId
  },
  author_id: { // 用户的ID
    type: mongoose.Schema.Types.ObjectId
  },
  author_name: { // 用户姓名
    type: String
  },
  description: String,
  content: String
})

module.exports = mongoose.model('Article', ArticleSchema, 'article')

用户表

const mongoose = require('./db')

// 用户表结构
const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true
  },
  password: String,
  name: String,
  age: Number,
  sex: String,
  tel: Number,
  status: {
    type: Number,
    default: 1
  }
})

module.exports = mongoose.model('User', UserSchema, 'user')

查询

查询文章信息并显示文章的分类以及文章的作者信息
ArticleModel.aggregate([
  {
    $lookup: {
      from: 'articlecate', // 关联的文档
      foreignField: '_id', // 关联文档对应的 _id 字段
      localField: 'cid', // 与当前文档中的 cid 字段进行关联查询
      as: 'cate', // 查询出来的结果放到该字段中
    }
  },
  {
    $lookup: {
      from: 'user', // 关联 user 文档
      foreignField: '_id', // 关联 user 文档对应的 _id 字段
      localField: 'author_id', // 使用当前文档的 author_id 字段进行关联
      as: 'user', // 查询出来的结果放到该字段中
    }
  }
], function (err, docs) {
  console.log(docs)
})

 

posted @ 2022-06-11 21:22  霸哥yyds  阅读(120)  评论(0)    收藏  举报