Mongoose populate with array of objects containing ref

前端 未结 4 572
旧巷少年郎
旧巷少年郎 2020-12-07 10:39

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 Sch         


        
相关标签:
4条回答
  • 2020-12-07 10:57

    Actual answer:

    Use this,

    populate('lists.list')
    

    Extra:

    Here are lists are an array of objects (list). In JS you can access this like that,

    console.log(lists.list);
    

    and MongoDB syntax is 99% similar to JS syntax. so you can also populate this using lists.list.

    0 讨论(0)
  • 2020-12-07 10:59
    lists: [
       {
          list: {
              type: Schema.ObjectId,
              require: true,
              ref: "List"
          },
          allocations: [
              {
                  type: Number,
                  required: true
              }
          ]
       }
    ],
    

    => Because it's an array of objects, you can do this -: Portfolio.populate('lists.list');

    2.

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

    => Because it's an array, you just have to do this -: Portfolio.populate('lists');

    0 讨论(0)
  • 2020-12-07 11:12
      // 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)
                            }
                        });
    
    0 讨论(0)
  • 2020-12-07 11:14

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

    0 讨论(0)
提交回复
热议问题