var articleSchema = new mongoose.Schema({
comments: {
},
// 关联字段==把分类的_id存在这
category: {
type: mongoose.Schema.Types.ObjectId,
// 引用 ref:后的是Classify模型
ref: "Classify"
},
})
//创建文章的时候给option的value绑定 分类的id
<select name="category" id="category" v-model="article.classify" >
<option v-for="(item,index) in classifyList" v-bind:value='item._id'>{{item.name}}</option>
</select>
// 发布文章的时候将分类的_id存进去
router.post('/article/create', (req, res) => {
var article = req.body
console.log(article)
new Article({
title: article.title,
content: article.content,
category:article.classify
}).save().then(rs=>{
res.send('200')
})
})
// 获取所有文章
//populate内是文章属性,这样一来category就保存了分类下的所有属性 ,前端想要调用就category.name,如果没有populate这一步存的仅仅是_id
router.get('/article/getlist',(req,res)=>{
Article.find().populate('category').then(doc=>{
console.log(doc)
res.send(doc)
})
})