【问题标题】:Mongoose populate, execPopulate not working猫鼬填充,execPopulate 不起作用
【发布时间】:2020-06-09 18:18:15
【问题描述】:

我有一个“部门”的猫鼬模型和另一个“课程”的模型。一对多的关系。在课程文档的部门字段下保存部门 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)
    })
})

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

【问题讨论】:

  • execPopulate() 已在猫鼬中删除。

标签: node.js mongodb express mongoose


【解决方案1】:

所以我在猫鼬文档中找到了解决方案。显然,'virtuals 默认不包含在 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}
})

【讨论】:

    猜你喜欢
    • 2014-12-19
    • 2013-06-20
    • 2016-12-24
    • 2014-05-01
    • 2021-02-03
    • 2018-06-10
    • 1970-01-01
    • 2015-07-13
    • 2016-10-10
    相关资源
    最近更新 更多