其他分享
首页 > 其他分享> > populate 关联查询

populate 关联查询

作者:互联网

模型

db.js

// 连接数据库
const mongoose = require('mongoose')

// eggadmin 用户名
// 123456 密码
// 127.0.0.1:27017 服务器及端口
// eggcms 数据库
mongoose.connect('mongodb://eggadmin:123456@127.0.0.1:27017/eggcms', function (err, data) {
  if (err) {
    console.log(err, '数据库连接成功')
    return;
  }
  console.log('数据库连接成功')
})

module.exports = mongoose

article.js (定义文档的时候需要使用 ref 来关联 model 模型名称)

const mongoose = require('./db')

// 文章表结构
const ArticleSchema = new mongoose.Schema({
  title: {
    type: String,
    unique: true
  },
  cid: { // 文章分类id
    type: mongoose.Schema.Types.ObjectId,
ref: 'Articlecate', // cid 外键与 Articlecate 模型关联 }, author_id: { // 用户的ID type: mongoose.Schema.Types.ObjectId,
ref: 'User', // author_id 外键关联 User 模型 }, author_name: { // 用户姓名 type: String }, description: String, content: String }) module.exports = mongoose.model('Article', ArticleSchema, 'article')

articlecate.js

const { Schema } = require('mongoose')
const mongoose = require('./db')

// 文章分类表
const ArticleCateSchema = new mongoose.Schema({
  title: {
    type: String,
    unique: true
  },
  description: String,
  addtime: {
    type: Date,
  }
})

module.exports = mongoose.model('ArticleCate', ArticleCateSchema, 'articlecate')

user.js

const mongoose = require('./db')

// 用户表结构
const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true
  },
  password: String,
  name: String,
  age: Number,
  sex: String,
  tel: Number,
  status: {
    type: Number,
    default: 1
  }
})

module.exports = mongoose.model('User', UserSchema, 'user')

查询

const ArticleCateModel = require('./model/articlecate')
const ArticleModel = require('./model/article')
const UserModel = require('./model/user')

ArticleModel.find({}).populate('cid').populate('author_id').exec(function (err, docs) {
  console.log(docs)
})

标签:const,String,populate,require,关联,mongoose,model,查询,type
来源: https://www.cnblogs.com/xiebenyin-/p/16367425.html