Populate Virtuals似乎不起作用。谁能告诉我这个错误?

问题描述 投票:0回答:1

我正在研究虚拟填充物: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;猫鼬教程声称它应该是“ Person的实例数组”。

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

第一:任何人都可以让我知道此代码有什么问题吗?我看不到它!

第二:如果要求不高,谁能向我展示这种技术的重要性。他们声称在速度上它比传统的填充更好,我目前的猫鼬知识我看不到它!

相关问题:Mongoosejs virtual populate

mongoose mongoose-populate
1个回答
0
投票

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

为了保持学习精神,我将在这里总结解决方案。

根据官方文件:

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

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

我一直在研究猫鼬官方教程,“认真吗?!伙计们,你可以改善!”我发现这很有挑战性。

© www.soinside.com 2019 - 2024. All rights reserved.