mongodb數據庫的集合關聯


通常不同集合的數據之間是有關系的,例如文章和用戶信息存儲在不同的集合中,但是文章時某個用戶發表的,要查詢文章的所有信息包括發表用戶,就需要用到集合關聯。

 

文章集合 用戶集合
_id _id
title name
author age

content

hobbies

 

示例:

const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost/test1', { useNewUrlParser: true })
  .then(() => console.log('數據庫連接成功'))
  .catch(err => console.log('數據連接失敗' + err))

// 文章集合規則
const PostSchema = new mongoose.Schema({
  title: String,
  content: String,
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
})

// 用戶集合規則
const UserSchema = new mongoose.Schema({
  name: String,
  age: Number,
  hobbies: String
})

// 文章集合
const post = mongoose.model('Post', PostSchema)
// 用戶集合
const user = mongoose.model('User', UserSchema)

// 創建用戶
user.create({ name: 'zhangsan', age: 20, hobbies: '11111' })
  .then(res => console.log(res))
  .catch(err => console.log(err))

// // 創建文章
post.create({ title: '測試測試', content: '內容內容內容內容', author: '5d34f0542fdc3f7924249a9c' })
  .then(res => console.log(res))
  .catch(err => console.log(err))

  // 查詢
post.find().populate('author').then(res => console.log(res))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM