首页 > 解决方案 > 在 Virtual Populate 中,如何定义 foreignField?

问题描述

考虑下面的代码:

 require("./connection");

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

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

const ManagerSchema = new Schema({
  name: String,
  country: 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 } 
});

BandSchema.virtual("managers", {
  ref: "Manager", // The model to use
  localField: "name", // Find people where `localField`
  foreignField: "country", // 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 } 
});

//BandSchema.set("toObject", { virtuals: true });
BandSchema.set("toJSON", { virtuals: true });

const Person = mongoose.model("Person", PersonSchema);
const Manager = mongoose.model("Manager", ManagerSchema);

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"
//   }
// ]);

// Manager.create([
//   {
//     name: "Bibi",
//     country: "South Africa"
//   },
//   {
//     name: "Storm",
//     country: "Italy"
//   },
//   {
//     name: "Wolverine",
//     country: "Canada"
//   },
//   {
//     name: "Jorge Pires",
//     country: "Brazil"
//   }
// ]);

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

const app = require("express")();

app.use("/", (req, res) => {
  Band.find({})
    .populate("members")
    .populate("managers")
    .exec(function(error, bands) {
      /* `bands.members` is now an array of instances of `Person` */
      console.log(bands);
      res.json(bands);
    });
});

app.listen(3000, () => {
  console.log("We are on port 3000");
});

/**
 *https://stackoverflow.com/questions/43882577/mongoosejs-virtual-populate
 https://stackoverflow.com/questions/60875380/populate-virtuals-does-not-seem-to-work-could-anyone-show-me-the-error
 */

考虑相关问题:

我的问题是:你如何定义foreignField

Members正确填充,但经理没有

我知道问题是foreignField因为如果我重复来自成员的所有信息,它将正确填充,但现在我们拥有成员并使用相同的数据源进行管理。

标签: mongoosemongoose-populate

解决方案


经过一些研究,试图在 Stack Overflow 上回答另一个问题(猫鼬:填充没有任何 ObjectId 的猫鼬 ),我意识到它是如何工作的!

考虑呈现的部分代码:

BandSchema.virtual("members", {
  ref: "Person", // The model to use
  localField: "name", // Find people where `localField`
  foreignField: "band", // this field here has to match the ref path we want to populate!      
  justOne: false,

});

所以,诀窍是确保foreignField匹配ref模型中的字段,并且localField是您可以在填充模型中找到的字段的名称:我们必须在 和 之间进行匹配foreignFieldlocalField更准确地说: 的值localField必须匹配在 foreignField实际情况下,在数据库中,而不是在模式命名过程中。这就是猫鼬可以找到和填充的方式!

现在我意识到我遇到的困难是它Virtual以某种相反的方向运作populate。您可以通过像树一样工作来描绘填充:它只是从文档填充id到文档,而virtual将填充不包含密钥的文档,包含密钥的文档是要在填充过程中添加的文档:它是莫名其妙地倒退了,这对我来说太难了!要填充的文档没有刚刚填充的字段!令人兴奋!

结论和最后的评论

尽管如此,与populate. 您仍然必须保留本地关键轨道,这并不能解决例如故事记忆问题,而且根据我的研究它更加有限。我看到的唯一优点是您不需要使用_id,您可以使用任何您喜欢的键。我希望在这里解决我的问题How to save an JSON file using GridFs,但由于我们仍然必须存储本地密钥,我陷入了同样的陷阱!

更正

我很高兴地说我错了!虚拟机太棒了!并解决了我关于如何使用 GridFs 保存 JSON 文件的问题,我将在那里更新!


推荐阅读