mongoose 多表关联
topic.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const TopicSchema = new Schema({
title:{
type:String
}
})
module.exports = mongoose.model('Topic',TopicSchema)
article.js
// const topic = require('./models/topic')
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ArtcleSchema = new Schema({
plate_id:{ //板块id
// 多表关联类型
type: Schema.Types.ObjectId,
// 需要关联的表名称
ref : 'Topic'
},
title:{ //标题
type:String,
required:true
},
····
})
module.exports = mongoose.model('Artcle',ArtcleSchema)
查询
// 详情
app.use('/topics/show',(req,res,next) => {
// 关联查询
Article
.findById(req.query.id)
.populate('plate_id') //需要查询的属性
.then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
})
})
效果
具体代码
github
https://github.com/laocaiq/node_mongodb_express_dome