简体   繁体   中英

Mongoose - Populate Object in Array

Using mongoose how can I populate a single object in an array?

For Example:

var SchoolSchema = new Schema({
  classes: [{
  name: String
  }]
});

var StudentSchema = new Schema({
  allocated_class: {
    type: ObjectId,
    ref: 'School'
  }
});

mongoose.model('School', SchoolSchema);
mongoose.model('Student', StudentSchema);

Student.find({}).populate("allocated_class").exec();

In the above example, how can I populate the name of the one class when finding all students?

Example data:

Student

{
    "allocated_class" : ObjectId("561e36540fc3c18b749d65e1"),
}

School

{
  "_id" : ObjectId("561e36320fc3c18b749d65e0"),
  "classes" : [ 
   {
      "name" : "Class 1",
      "_id" : ObjectId("561e36540fc3c18b749d65e1")
   }]
}

The end result should be the student collection populated with the name of their allocated class.

Try this

var StudentSchema = new Schema({
  name:{type: String, unique: true},
  allocated_class: [schoolSchema]
});

even if not like this - you should make the change in schema. One school has many classes, One student has many classes, so (new) Classes Schema could be the connection between school and student.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM