填充 Virtuals 似乎不起作用。谁能告诉我错误?

Populate Virtuals does not seem to work. Could anyone show me the error?

我正在研究 Populate Virtuals:https://mongoosejs.com/docs/populate.html#populate-virtuals

require("./connection");

// //----------------------------------------------------
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const PersonSchema = new Schema({
  name: String,
  band: String
});

const BandSchema = new Schema({
  name: String
});

BandSchema.virtual("members", {
  ref: "Person", // The model to use
  localField: "name", // Find people where `localField`
  foreignField: "band", // is equal to `foreignField`
  // If `justOne` is true, 'members' will be a single doc as opposed to
  // an array. `justOne` is false by default.
  justOne: false,
  options: { sort: { name: -1 }, limit: 5 } 
});

const Person = mongoose.model("Person", PersonSchema);
const Band = mongoose.model("Band", BandSchema);

/**
 * Suppose you have 2 bands: "Guns N' Roses" and "Motley Crue"
 * And 4 people: "Axl Rose" and "Slash" with "Guns N' Roses", and
 * "Vince Neil" and "Nikki Sixx" with "Motley Crue"
 */
// Person.create([
//   {
//     name: "Axl Rose",
//     band: "Guns N' Roses"
//   },
//   {
//     name: "Slash",
//     band: "Guns N' Roses"
//   },
//   {
//     name: "Vince Neil",
//     band: "Motley Crue"
//   },
//   {
//     name: "Nikki Sixx",
//     band: "Motley Crue"
//   }
// ]);

// Band.create([{ name: "Motley Crue" }, { name: "Guns N' Roses" }]);
/////////////////////////////////////////////////////////////////////////

Band.find({})
  .populate("members")
  .exec(function(error, bands) {
    /* `bands.members` is now an array of instances of `Person` */
    console.log(bands.members);
  });

然而,这段代码的输出是undefined;猫鼬教程声称它应该是 "an array of instances of Person"。

我测试了另一个代码,但我得到了类似的结果:http://thecodebarbarian.com/mongoose-virtual-populate.html

首先:谁能告诉我这段代码有什么问题?我看不到!

其次:如果不是要求太多,谁能告诉我这个技术的重要性。他们声称它在速度方面比传统的填充更好,我目前的猫鼬知识看不到它!

相关问题:

答案就在眼前!我所涉及的问题,即毕竟有答案:

为了保持学习的精神,我把解决方法总结在这里。

根据官方文档:

If you use toJSON() or toObject() mongoose will not include virtuals by default.

参见:https://mongoosejs.com/docs/guide.html#virtuals

老实说,我不知道那是什么意思,但它包含在评论中,似乎是答案!

因此,需要做的是包含以下行:

BandSchema.virtual("members", {
  ref: "Person", // The model to use
  localField: "name", // Find people where `localField`
  foreignField: "band", // is equal to `foreignField`
  // If `justOne` is true, 'members' will be a single doc as opposed to
  // an array. `justOne` is false by default.
  justOne: false,
  options: { sort: { name: -1 }, limit: 5 }
});
//----------------------------------------------------------------    
//here, this one! 
    BandSchema.set("toObject", { virtuals: true });
    BandSchema.set("toJSON", { virtuals: true });

//------------------------------------------

一直在研究mongoose官方教程,"seriously?! guys, you can improve!"觉得很有挑战性。