【问题标题】:Mongoose populate with array of objects containing refMongoose 填充包含 ref 的对象数组
【发布时间】:2013-05-14 12:29:39
【问题描述】:

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

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'),但我要么没有正确调用事物,要么我的架构没有正确形成。如果我只是自己引用列表,我没有这个问题:

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

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

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    我找到了答案:populate('lists.list') 有效。感谢这个问题:Mongoose populate within an object?

    【讨论】:

    • 嗨,朋友,我想念的任何东西都不适合我。我还没有使用必需的。
    • 它对我有用。我正在为服务数组中的每个服务填充谢谢。 services:[{ quantity: Number, service: { type:Schema.Types.ObjectId, ref: 'vas' } }],
    • 谢谢,它的工作,你真的拯救了我的一天。
    【解决方案2】:
    lists: [
       {
          list: {
              type: Schema.ObjectId,
              require: true,
              ref: "List"
          },
          allocations: [
              {
                  type: Number,
                  required: true
              }
          ]
       }
    ],
    

    => 因为它是一个对象数组,所以你可以这样做 -: Portfolio.populate('lists.list');

    2.

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

    => 因为它是一个数组,所以你只需要这样做 -: Portfolio.populate('lists');

    【讨论】:

    • 如何在此处填写 adminId? adminInfo: { _id: false, adminId: [{ type: Schema.Types.ObjectId, ref: 'User' }] }
    • XYZ.populate('adminInfo.adminId');
    • 已经试过了请看这里:stackoverflow.com/questions/62531177/…
    • 第一个有效,但第二个无效。知道为什么吗?
    【解决方案3】:

    实际答案:

    使用这个,

    populate('lists.list')
    

    额外:

    这里的列表是一个对象数组(列表)。 在JS中你可以这样访问,

    console.log(lists.list);
    

    MongoDB 语法与 JS 语法有 99% 的相似性。 所以…………

    【讨论】:

    • 如何在此处填写 adminId? adminInfo: { _id: false, adminId: [{ type: Schema.Types.ObjectId, ref: 'User' }] }
    【解决方案4】:

    如果您有嵌套架构

    YourSchema.find()
       .populate({
            path: 'map_data',
            populate: {
                path: 'location' 
            }
    })
    

    对我有用

    【讨论】:

      【解决方案5】:
        // Cart schema  
      
       var CartSchema = new mongooseSchema({
              productDetails: [
                  {
                      productId: {
                          type: mongoose.Schema.ObjectId,
                          required: true,
                          ref:'Product'
      
                      },
                      productCount: Number,
                  }
              ],
              UserId: {
                  type: String,
                  default: '',
                  required: true,
                  trim: true,
              },
              shopId: {
                  type: String,
                  default: '',
                  required: true,
                  trim: true,
              },
          });
      
        // add this .populate('productDetails.productId').
      
               db.Cart.find({
                              UserId: userId,
                              shopId: shopId
                          }).populate('productDetails.productId').skip(pagination.skip).limit(pagination.limit).exec(function (error, CartList) {
      
                              if (error) {
                                  callback(error, null)
                              } else {
                                  callback(null, CartList)
                              }
                          });
      

      【讨论】:

        【解决方案6】:

        在我的 Schema 嵌套数组时,填充在我的情况下不起作用

        const chatSchema = mongoose.Schema({
            chats: [
            {
             type: Schema.Types.ObjectId,
             ref: "ChatMsg" },
           ],
          })
        

        我是怎么解决的

        Chat.findOne(
         { customer: req.body.customer, agency: req.body.agency },
          (err, chat) => {
           if (err) {
            res.status(422).send("Our fault");
           }
            chat.populate("chats").execPopulate(() => {
            res.send(chat);
           });
          }
        );
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-01-23
          • 2020-11-03
          • 1970-01-01
          • 2023-02-01
          • 2022-01-24
          • 2016-01-19
          • 2019-09-23
          • 2020-06-01
          相关资源
          最近更新 更多