MongoDB集合关联

集合关联

通常不同集合的数据之间是有关系的, 例如文章信息和用户信息存储在不同的集合中, 但是文章是某个用户发表的, 要查询文章的所有信息包括发表用户, 就需要用到集合关联.

  • 使用id对集合进行关联
  • 使用populate方法进行关联集合查询
    在这里插入图片描述

集合关联实现

const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
  .then(() => console.log('数据库连接成功'))
  .catch(err => console.log(err, '数据库连接失败'))

// 用户集合规则
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }
})

// 文章集合规则
const postSchema = new mongoose.Schema({
  title: {
    type: String
  },
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
})

// 用户集合
const User = mongoose.model('User', userSchema)

// 文章集合
const Post = mongoose.model('Post', postSchema)
  • 创建用户
User.create({name: 'zhanshan'}).then(result => console.log(result))
  • 创建文章
Post.create({title: '123', author: '5f117e39fed22c4cd83d51d0'})
  .then(result => console.log(result))
  • 查询信息
Post.find().populate('author').then(result => console.log(result))

猜你喜欢

转载自blog.csdn.net/weixin_47085255/article/details/107414982