猫鼬填充,execPopulate不起作用

时间:2020-06-08 16:58:14

标签: node.js mongodb express mongoose

我有一个“部门”的猫鼬模型和另一个“课程”的猫鼬模型。一对多的关系。在课程文档的部门字段下保存部门ID。我想查询所有部门,并在一个请求中填充所有课程。 这是课程模式的代码

const mongoose = require('mongoose')


const courseSchema = new mongoose.Schema(
{
name:{
        type: String,
        trim: true,
        required: true
    },
 department:{
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Department'
    }
module.exports = mongoose.model('Course', courseSchema)

在这里输入部门代码

const mongoose = require('mongoose')
const validator = require('validator')
const bcrypt = require('bcryptjs')
const departmentSchema = new mongoose.Schema({
 title:{
        type: String,
        required: true
    },
admin: {
        type: mongoose.Schema.Types.ObjectId,
        trim: true,
    }
departmentSchema.virtual('courses',{
    ref: 'Course',
    localField: '_id',
    foreignField: 'department'
})
const Department = mongoose.model(' Department',departmentSchema)

module.exports = Department

这是所有部门的招募路线

router.get('/departments', async (req, res)=>{
    Department.find().populate('courses').exec(function (err, departments) {
        if (err) {
            res.status(500).send(err)
        }
        res.status(200).send(departments)
    })
})

此代码仅返回部门,而不会填充课程数组。

1 个答案:

答案 0 :(得分:0)

所以我在猫鼬文档中找到了解决方案。显然,默认情况下,“虚拟”不包含在toJSON()输出中。如果您想在使用依赖于JSON.stringify()的函数(例如Express的res.json()函数)时显示虚拟对象,请在架构的toJSON选项上设置virtuals:true选项。 所以我修改了部门架构,使其看起来像这样

const departmentSchema = new mongoose.Schema({

    title:{
        type: String,
        required: true
    },
    admin: {
        type: mongoose.Schema.Types.ObjectId,
        trim: true,
        ref: 'User'
    }

},{
    timestamps: true,
    toJSON: {virtuals: true}
})