首页 > 其他 > 详细

mongoose关联表结构

时间:2017-08-24 18:33:28      阅读:302      评论:0      收藏:0      [点我收藏+]

 

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)
    })
})

 

mongoose关联表结构

原文:http://www.cnblogs.com/wuyushuo/p/7424370.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!