Я изучаю официальную документацию mon goose (https://mongoosejs.com/docs/populate.html#dynamic -ref ), и я нашел этот пример:
//------------------------------------------------------------------
require("./connection");
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
//---------------------------------------------------------------
const commentSchema = new Schema({
body: { type: String, required: true },
modelId: {
type: Schema.Types.ObjectId,
required: true,
// Instead of a hardcoded model name in `ref`, `refPath` means Mongoose
// will look at the `modelName` property to find the right model.
refpath: "modelId.modelName2"
},
modelName2: {
type: String,
required: true,
enum: ["BlogPost", "Product"]
}
});
const Product = mongoose.model("Product", new Schema({ name: String }));
const BlogPost = mongoose.model("BlogPost", new Schema({ title: String }));
const Comment = mongoose.model("Comment", commentSchema);
//-----------------------------------------------------------------
rockit();
//-------------------------------------------------------------------
async function rockit() {
const book = await Product.create({ name: "The Count of Monte Cristo" });
const post = await BlogPost.create({ title: "Top 10 French Novels" });
const commentOnBook = await Comment.create({
body: "Great read",
modelId: book._id,
modelName2: "Product"
});
const commentOnPost = await Comment.create({
body: "Very informative",
modelId: post._id,
modelName2: "BlogPost"
});
// The below `populate()` works even though one comment references the
// 'Product' collection and the other references the 'BlogPost' collection.
const comments = await Comment.find()
.populate("modelId")
.sort({ body: 1 });
console.log(comments[0].modelId.name); // "The Count of Monte Cristo"
console.log(comments[1].modelId.title); // "Top 10 French Novels"
}
Этот пример представляет собой смесь официальная документация, которая не работает, и следующий пост: https://github.com/Automattic/mongoose/issues/7967
Но я все еще не могу заставить его работать, он не заполняется, как предполагается. Любой