本文介绍了Mongoose 填充包含 ref 的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Mongoose 模式,其中包含一个对象数组 lists,其中包含对另一个集合的引用和一个嵌套的数字数组:

I have a Mongoose schema with an array lists of objects that consist of a reference to another collection and a nested array of numbers:

var Schema, exports, mongoose, schema;

mongoose = require("mongoose");

Schema = mongoose.Schema;

schema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  lists: [
    {
      list: {
        type: Schema.ObjectId,
        require: true,
        ref: "List"
      },
      allocations: [
        {
          type: Number,
          required: true
        }
      ]
    }
  ],
  createdAt: {
    type: Date,
    "default": Date.now
  },
  updatedAt: {
    type: Date
  }
});

exports = module.exports = mongoose.model("Portfolio", schema);

但是,如果没有 TypeError: Cannot read property 'ref' of undefined,我无法让 populate 按预期工作.我试过 populate('list')populate('lists list') 但我要么没有正确调用东西,要么我的架构没有正确形成.如果我只是自己引用列表,我就不会有这个问题:

However, I cannot get populate to work as expected without getting a TypeError: Cannot read property 'ref' of undefined. I've tried populate('list') and populate('lists list') but I'm either not calling things correctly or my Schema isn't formed correctly. I don't have this problem if I simply reference the lists by themselves:

lists: [
    {
        type: Schema.ObjectId,
        require: true,
        ref: "List"
    }
  ]

但我想在每个列表旁边都有分配数组.我需要做什么才能获得我想要的行为?

but I want to have the allocations array alongside each list. What do I need to do to get the behavior I want?

推荐答案

我找到了答案:populate('lists.list') 有效.感谢这个问题:Mongoose 在对象中填充?

I found the answer: populate('lists.list') works. Thanks to this question: Mongoose populate within an object?

这篇关于Mongoose 填充包含 ref 的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 09:14