文章列表字段 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
})
}
});
响应的 tab 为空。和联合查询一样
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…