I have a mongoose schema that defines an author.
我有一个定义作者的猫鼬模式。
const mongoose = require("mongoose");
const schema = new mongoose.Schema(
{
fullname: {
type: String,
required: true,
trim: true,
},
book: {
type: mongoose.Schema.Types.ObjectId,
ref: "book",
},
}
const Authors = mongoose.model("author", schema);
module.exports = Authors;
Now I have a schema that defines the book.
现在我有了定义这本书的模式。
const mongoose = require("mongoose");
const schema = new mongoose.Schema(
{
bookname: {
type: String,
required: true,
trim: true,
},
}
const Books = mongoose.model("book", schema);
module.exports = Books;
Normally I would use a query like
const author = await Author.findOne({ fullname: "bob"}).populate("book")
通常,我会使用类似Const Author=await Author.findOne({fullname:“bob”}).panate(“book”)这样的查询
Is there a way to use the author schema to auto populate the book data so I don't have to make the population on the query? I see it as way more efficient to do it in the schema than through out the code. So the final output would be from the populate/auto populate would be
有没有一种方法可以使用AUTHER模式自动填充图书数据,这样我就不必对查询进行填充了?我认为在模式中这样做比通过代码来做更有效。因此,填充/自动填充的最终输出将为
{
fullname: "bob",
book: {
name: "joy of coding",
},
}
Thanks for your ideas.
谢谢你的点子。
更多回答
优秀答案推荐
In the author modal make sure you include the book model.
在作者模式中,确保包括图书模型。
const book = require("./book")
const book = require(“./书”)
Then you need to add the pre("findOne") hook
然后需要添加pre(“findOne”)钩子
schema.pre("findOne", function (next) {
this.populate("book");
next();
});
So your query would be simply const author = await Author.findOne({ fullname: "bob"});
因此,您的查询应该是const Author=await Author.findOne({fullname:“Bob”});
If you have more children to populate you can add them into this one pre hook and all of the child data will be gathered and returned as one document.
如果您有更多的子项要填充,您可以将它们添加到这个预挂接中,所有的子项数据都将被收集并作为一个文档返回。
更多回答
The name of the pre hook "findOne" has to match the query you are doing, so this pre hook would not work for a "find" query. You would need to create the pre hook for each kind of query you would need to make in your code.
前挂钩“findOne”的名称必须与您正在执行的查询匹配,因此这个前挂钩不适用于“Find”查询。您需要为需要在代码中进行的每种查询创建前挂钩。
我是一名优秀的程序员,十分优秀!