Mongoose填充,execPopulate不工作

p1iqtdky  于 2022-12-19  发布在  Go
关注(0)|答案(2)|浏览(114)

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

这段代码只返回部门,而不填充courses数组。

7gcisfzg

7gcisfzg1#

所以我在mongoose文档中找到了解决方案。显然,默认情况下,“virtuals”不包含在toJSON()输出中。如果您希望在使用依赖于JSON.stringify()的函数(如Express的res.json()函数)时显示populate virtuals,请设置virtuals:模式的toJSON选项上的true选项。“所以我修改了我的department模式,如下所示

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}
})
w1e3prcc

w1e3prcc2#

const userSchema = new Schema(
    {
    name: {
      type: String,
      require: true,
    },

    email: {
      type: String,
      require: true,
    },

    cart: {
      items: [
        {
          productId: {
            type: Schema.Types.ObjectId,
            ref: "Product",
            require: true,
          },

          quantity: {
            type: Number,
            require: true,
          },
        },
      ],
    },
  },

  // becuase the execPopulate() doens't work 
  //.. we fix the issue with this code addition
  // !!! execPopulate() function was removed from mongoose db !!!

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

相关问题