Я не могу видеть работу виртуального населения - PullRequest
0 голосов
/ 30 марта 2020

Я пытаюсь изучить работу Виртуального населения, поскольку они утверждают, что оно может быть лучше, чем обычное население. Поскольку у меня есть огромный набор данных, связанный с небольшим документом, я подумал: «возможно, было бы разумно создать этот огромный набор данных отдельно и соединить их с помощью Virtual Populate», но… я не могу ясно видеть работу Virtual Populate.

Я проверил два кода, см. Ниже, ни один из них не доставляет то, что я хочу, или что они обещают. Может быть, я что-то упустил, кто-нибудь?

Обсуждение

Код 1 ближе к тому, что я хочу, так как он просто заполняет часть коллекции, основываясь на id, видите, он использует mongoose.Schema.Types.ObjectId; код 2 не использует идентификатор, поэтому заполняет все, это не то, что я хочу; для каждого документа, который я хочу заполнить, просто заполните соответствующие, так как набор данных огромен, я надеялся, что виртуальный может быть лучшим, но пока я не могу понять, как код 1 не работает, как обещано! Тем не менее, код 1 не работает, как обещано, вы должны выполнить традиционное заполнение.

Я задаю вопрос, потому что я могу что-то упустить, и любое предложение может быть приветствоваться!

Код 1 Источник : http://thecodebarbarian.com/mongoose-virtual-populate.html

//------------------------------------------------------
require("./connection");

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

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

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

// Specifying a virtual with a `ref` property is how you enable virtual
// population
AuthorSchema.virtual("posts", {
  ref: "BlogPost",
  localField: "_id",
  foreignField: "author"
});

const BlogPostSchema = new Schema({
  title: String,
  author: { type: mongoose.Schema.Types.ObjectId, ref: "Author" },
  comments: [
    {
      author: { type: mongoose.Schema.Types.ObjectId, ref: "Author" },
      content: String
    }
  ]
});

const Author = mongoose.model("Author", AuthorSchema, "Author");
const BlogPost = mongoose.model("BlogPost", BlogPostSchema, "BlogPost");


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

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

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

Код 2 Источник : https://mongoosejs.com/docs/populate.html#populate -виртуалы

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

BandSchema.virtual("managers", {
  ref: "Manager", // 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.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);

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