Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

mongoose 联合查询 populate

文章列表字段 classUuid 和 分类列表字段 uuid对应的,怎么可以查文章联合分类表中的 tabname 字段查出来,关于populate的使用看了很多例子然后然后都不对,以下是代码:

//代码已经修改为聚合查询
//文章model article.js
const mongoose = require('mongoose');

const Schema = mongoose.Schema;
let articleSchema = new Schema({
  classUuid: {
    type: String,
    required: true,
  },
  uuid:{
      type:String,
      unique: true,
      required: true
  },
  author:{
      type:String,
      required:true
  },
  title:{
      type:String,
      required: true
  },
  content:{
      type:String,
      required: true
  },
  created_time:{
      type:String,
      default:() => +new Date()
  },
  updated_time:{
      type:String
  }
});
 module.exports = mongoose.model('articleSchema',articleSchema);


//分类 classification.js
const mongoose = require('mongoose');
let Schema = mongoose.Schema;
let classSchema = new Schema({
  tabname: {
    type: String,
    required: true,
    unique:true,
  },
  uuid:{
      type:String,
      unique: true,
      required: true
  },
  remarks:{
      type:String
  }
});

 module.exports = mongoose.model('classSchema', classSchema);
 
 
 
 
 
 
    //文章列表查询接口
        article.find({
            $or: [{
                classUuid:{
                    $regex: new RegExp(classUuid)
                },
                title: {
                    $regex: reg
                }
            }]
        }).aggregate([
                {
                  $lookup: {
                    from: "classSchema", //分类
                    localField: "classUuid", //文章表需要关联的字段
                    foreignField: "uuid", //分类表中的 uuid,对应文章表中的 classUUid
                    as: "tab"
                  }]).sort({'created_time':-1}).skip((pageNum - 1) * pageSize).limit(+pageSize).exec(function(err, data) {
            if (err) {
                res.json({
                    status: 0,
                    message: 'error'+err
                })
            } else {
                
                res.json({
                    status: 0,
                    message: 'success',
                    data,
                    count:total
                })
            }

        });

image.png

响应的 tab 为空。和联合查询一样


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

使用ObjectId作为type
uuid: [{ type: mongoose.Schema.Types.ObjectId, ref: 'classSchema' }]

使用上:.populate('classSchema')会把classSchema下面的所有字段查出来,就可以获取你想要的tabname

也可以使用聚合管道aggregate

image.png

有些注意项:

  1. 使用聚合管道的模型是那个
  2. from这个字段会是小写并结为带有s

具体你还是看看聚合管道aggregate


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...