Mongoose 多表(N个表)关联查询概述
需求:文章(article),文章分类(articlecate),用户(user)这三个表之间的关系,一篇文章对应文章分类表中的某个类型,对应着用户表中的某个用户
Mongoose 多表(N个表)关联查询代码实现
首先我们需要创建db.js(连接数据库)的模块
var mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/eggcms',{ useNewUrlParser: true },function(err){ if(err){ console.log(err); return; } console.log('数据库连接成功') }); module.exports = mongoose;
通过上面的需求我们需要建立三个model模块分别是article.js,articlecate.js,user.js
var mongoose = require('./db.js'); var Schema = mongoose.Schema; var ArticleSchema = new Schema({ title: { type: String, unique: true }, cid: { // 分类id type: Schema.Types.ObjectId }, author_id:{ // 用户的id type: Schema.Types.ObjectId }, author_name:{ type:String }, descripton: String, content: String }); module.exports = mongoose.model('Article',ArticleSchema,'article');
var mongoose = require('./db.js'); var ArticleCateSchema = new mongoose.Schema({ title : { type: String, unique: true }, descripton: String, addtim