通常不同集合的数据之间也是有关联的,例如文章信息和用户信息存在不同的集合中,但是文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联
- 使用id对集合进行关联
- 使用populate方法进行关联集合查询
const mongoose = require("mongoose");
//连接数据库
mongoose.connect("mongodb://localhost/playground").then(() => {
console.log("连接成功")
}).catch(e => {
console.log("连接失败",e);
})
// 创建集合规则
const userSchema = new mongoose.Schema({
name: {
type:String
},
age: {
type: Number
}
})
const postSchema = new mongoose.Schema({
title: {
type: String
},
author:{
type:mongoose.Schema.Types.ObjectId,
ref:"User"
},
content:{
type:String
}
})
const User = mongoose.model("User",userSchema);
const Post = mongoose.model("Post",postSchema);
// User.create({name:"张三",age:20}).then(res => {
// console.log(res)
// })
// Post.create({title:"hm",author:"62442bacc72bbce4a08a3ad8",content:"哈哈哈哈哈哈"})
Post.find().populate("author").then(res => {
console.log(res)
})