Consider the code below:
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
*/
Consider the related questions:
My question is: how do you define foreignField
?
Members
populate properly, but manager does not.
I know the problem is foreignField
because if I repeat all the information from members, it will populate properly, but now we have members and manage with the same data source.