Populating an array when creating a record in MongoDB with mongoose

I am writing an application that keeps track of members and their certifications. Each member has some arrays that refer to other models as described in the Mongoose population docs.

Member schema
{
  name: {
    first: String,
    last: String
  },
  unit: Number,

  // more stuff

  class_year: Number,
  campus_box: String,
  campus_address: String,

  // more stuff

  emails: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Email' }],
  certifications: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Certification' }],
  service_credits: [{ type: mongoose.Schema.Types.ObjectId, ref: 'ServiceCredit' }]
}
Certification schema
{
  type: String,
  issue: Date,
  expiry: Date,
  number: String,
  _member: { type: mongoose.Schema.Types.ObjectId, ref: 'Member' }
}

The schemata for Email and ServiceCredit are similar in that they both have the _member field.

When I create an Email, it is added to the Email model and I can subsequently perform

var Email = mongoose.model('Email');
Email.findOne().populate('_member').exec(function (err, email) {
  console.log(email._member.name.first);
});

However, it is not added to the array in the Member schema, because when I run

var Member = mongoose.model('Member');
Member.findOne().populate('emails').exec(function (err, member) {
  res.json(200, member);
});

I get emails: [] in the JSON, when there is clearly an Email associated with that member.

I have read on the Mongoose API that the document itself needs to be populated, so I'm trying to do what is referenced at http://mongoosejs.com/docs/api.html#document_Document-populate with the following:

var Member = mongoose.model('Member');
Member.findOne({ _id: req.session.member._id }, function (err, member) {
  member.populate('emails', function (err) {
    console.log('populated emails');
  });
});

But I get the error: (member's JSON data) has no method 'populate'. I know I'm trying to run populate on the wrong thing, but I can't figure out what the correct way would be.

Answers


I've also encountered issues with populating array, the schema you defined will create a sub-doc for each array element (try dumping the array).

Try changing the schema to:

emails: [ type: mongoose.Schema.Types.ObjectId ]

and use

Member.findOne().populate({ path: 'emails', model: 'Email' }).exec(function (err, member) {
    res.json(200, member);
});

to populate the array.


Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.