在Mongoose中从另一个模式加载数据查询



我正在尝试改进get查询。

目标是获得所有Authors和所有Posts上的喜欢总数。这是我的实现。

const authors = await Author.find({ created_at: -1 }).lean();
const updated = authors.map((author) => {
const likes = await Post.find({ authorId: author._id }).select({ likes: 1 });
return { ... author, likes };
});

返回一个promise数组。但是,等效的for循环可以完成这项工作。

是否有一种方法可以更好地实现这一点,而不是通过整个集合循环并为每个集合获取likes?

即使你的问题是一年前的,为了帮助未来的访问者,你可能需要的解决方案可能是population()猫鼬的方法

Population,指定应该用其他文档填充的路径。

let book = await Book.findOne().populate('authors');
book.title; // 'Node.js in Action'
book.authors[0].name; // 'TJ Holowaychuk'
book.authors[1].name; // 'Nathan Rajlich'
let books = await Book.find().populate({
path: 'authors',
// `match` and `sort` apply to the Author model,
// not the Book model. These options do not affect
// which documents are in `books`, just the order and
// contents of each book document's `authors`.
match: { name: new RegExp('.*h.*', 'i') },
sort: { name: -1 }
});
books[0].title; // 'Node.js in Action'
// Each book's `authors` are sorted by name, descending.
books[0].authors[0].name; // 'TJ Holowaychuk'
books[0].authors[1].name; // 'Marc Harter'
books[1].title; // 'Professional AngularJS'
// Empty array, no authors' name has the letter 'h'
books[1].authors; // []

参考:https://mongoosejs.com/docs/populate.html

最新更新