把需要关联的字段设置成关联集合的ObjectID值。上图理解
const user = mongoose.model('User',new mongoose.Schema({
name:{type:String}
}))
const article = mongoose.model('Post',new mongoose.Schema({
title:{type:String},
author:{
type:mongoose.Schema.Types.ObjectID,
ref:user
}
}))
async function async() {
let res = await user.create({name:'斯提芬金'})
await article.create({title:'肖申克的救赎', author:res._id})
return article.find()
}
async().then(res=>{
console.log(res)
})
建了一个用户表,只有一个name字段,再建了一个ariticle表,他的作者字段要关联到user集合。所以把作者的type设置成
mongoose.Schema.Types.ObjectID 这是重点。
由于是异步操作,我用了async函数进行顺序控制。可以看到此时输出的数据是这样的
这显然不是我们想要的数据,我们想要author显示信息,而不是一个地址值。此时find函数改写成这样。
article.find().populate('author')
此时再来查看显示信息
成功!