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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值