我正在尝试在猫鼬中创建一种自定义查询方法 - 类似于mongoose的pupulate((函数。我有以下两个简单的模式:
const mongoose = require('mongoose'(
const bookSchema = new mongoose.Schema({
title: String,
author: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Author'}
}, {versionKey: false})
const authorSchema = new mongoose.Schema({
name: String
}, {versionKey: false})
现在,我想检索作者的信息,并进一步由作者写的书。据我所知,Mongoose提供自定义查询,因此我的想法是编写一个自定义查询功能:
authorSchema.query.populateBooks = function () {
// semi-code:
return forAll(foundAuthors).findAll(books)
}
现在,要获得所有作者和所有书籍,我可以简单地运行:
authormodel.find({}(。
这应该导致这样的事情:
[ {name: "Author 1", books: ["Book 1", "Book 2"]}, {name: "Author 2", books: ["Book 3"] } ]
不幸的是,它不起作用,因为我不知道如何访问填充书功能中先前选择的作者列表。我在自定义查询功能中需要的是以前选择的文档的收集。例如,AechorModel.find({}(已经返回了作者列表。在填充书((中,我需要遍历此列表,以找到所有作者的所有书籍。任何人都知道我如何访问此集合或是否可能?
填充:"人口是用其他集合中的文档自动替换文档中指定路径的过程"(来自我链接的文档(。
根据您的问题,您不是在寻找人口。您的查询是一个简单的查询(以下代码是要达到最后给出的示例结果。请注意,您的书籍字段具有各种字符串的值,我认为这些字符是标题(。另外,请注意,以下代码将与您已经提供的模型一起使用,但这是我建议的不良实现 - 出于多种原因:效率,优雅,潜在错误(例如,具有相同名称的作者(,请参阅代码之后的注:
Author.find({}, function(err, foundAuthors){
if (err){
console.log(err); //handle error
}
//now all authors are objects in foundAuthors
//but if you had certain search parameters, foundAuthors only includes those authors
var completeList = [];
for (i=0;i<foundAuthors.length;i++){
completeList.push({name: foundAuthors[i].name, books: []});
}
Book.find({}).populate("author").exec(function(err, foundBooks){
if (err){
console.log(err); //handle err
}
for (j=0;j<foundBooks.length;j++){
for (k=0;k<completeList.length;k++){
if (completeList[k].name === foundBooks[j].author.name){
completeList[k].books.push(foundBooks[j].title);
}
}
}
//at this point, completeList has exactly the result you asked for
});
});
但是,正如我所说,我建议反对此实施,这是基于您已经提供的代码而不更改它的代码。
我建议更改您的作者模式以包括一本书的财产:
var AuthorSchema = new mongoose.Schema({
books: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Book"
}]
//all your other code for the schema
});
并将所有书籍添加到各自的作者中。这样,您需要做的一切才能获得一系列对象,每个对象都包含作者,他的所有书籍都是一个查询:
Author.find({}).populate("books").exec(function(err, foundAuthors){
//if there's no err, then foundAuthors is an array of authors with their books
});
比我已经存在的代码不更改它更简单,更高效,更优雅,更有效。