zoukankan      html  css  js  c++  java
  • Mongoose 中使用 populate 实现关联查询

    一、Mongoose populate 官方文档
    https://mongoosejs.com/docs/populate.html

    二、Mongoose populate 关联查询

    article.js

    var mongoose=require('./db.js');
    var Schema=mongoose.Schema;
    
    var ArticleSchema = new Schema({
        title:{ 
            
            type: String, unique: true     
        },
        cid : { 
            
            type: Schema.Types.ObjectId,   
            ref:"ArticleCate"    //cid和 文章分类建立关系。   model    
        },   /*分类 id*/
    
        author_id:{        
            type: Schema.Types.ObjectId ,
            ref:"User"    //author_id和 用户表建立关系。   model
        },   /*用户的id*/
        author_name:{        
            type:String      
        },
        descripton:String,   
        content   : String
    });
    
    
    module.exports=mongoose.model('Article',ArticleSchema,'article');
    //注意使用 populate需要引入用到的model
    var ArticleCateModel=require('./model/articlecate.js');
    var ArticleModel=require('./model/article.js');
    var UserModel=require('./model/user.js');
    
    
    
    //文章表和 分类表的关联
        // ArticleModel.find({}).populate('cid').exec(function(err,docs){
        //     console.log(docs);
        // })
    
    
    //三个表关联
    ArticleModel.find({}).populate('cid').populate('author_id').exec(function(err,docs){
            console.log(docs);
    })
    
    // ArticleModel.aggregate  建议使用
  • 相关阅读:
    nginx 启动相关的
    爬取豆瓣读书/文件存储数据/数据库存储数据
    python Web 开发三剑客比较
    scrapy
    爬虫自动登录抽屉
    组合搜索
    html瀑布流
    Ajax上传文件/文件预览
    Form组件
    django分页
  • 原文地址:https://www.cnblogs.com/loaderman/p/11516496.html
Copyright © 2011-2022 走看看