Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose populate with array of objects containing ref

Tags:

mongoose

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); 

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?

like image 562
neverfox Avatar asked May 20 '13 01:05

neverfox


People also ask

What does REF do in Mongoose?

The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.

What is $Push in Mongoose?

$push. The $push operator appends a specified value to an array. The $push operator has the form: { $push: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.


2 Answers

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

like image 166
neverfox Avatar answered Sep 28 '22 19:09

neverfox


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');

like image 37
Sonu Bhatt Avatar answered Sep 28 '22 18:09

Sonu Bhatt