我正在研究填充虚拟机: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虚拟填充
答案就在我眼前!我所涉及的问题毕竟有答案: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 });
//------------------------------------------
我一直在研究猫鼬官方教程,“认真吗?!伙计们,你可以改善!” 我发现这很有挑战性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句