【发布时间】:2021-07-24 11:34:18
【问题描述】:
我正在尝试使用聚合来替换代码中的填充。我正在显示所有带有媒体的帖子作为媒体文件的路径。
我的帖子模型如下所示
const { model, Schema, Types } = require("mongoose");
const postSchema = new Schema(
{
description: {
type: String,
required: false,
},
views: {
type: Number,
default: 0,
},
user: {
type: Schema.Types.ObjectId,
ref: "user",
},
media: {
type: Schema.Types.ObjectId,
ref: "media",
required: false,
},
comments: [
{
type: Schema.Types.ObjectId,
ref: "comment",
},
],
// 1 lakh comments
// comment ma pagination
// total_comment = 100000
likes: [{ type: Schema.Types.ObjectId, ref: "user" }],
},
{
timestamps: { createdAt: "created_at", updatedAt: "updated_at" },
}
);
postSchema.methods.isOwner = function ({ _id, is_admin }) {
return is_admin || this.user.equals(_id);
};
module.exports = new model("post", postSchema);
为 GET 路由 /all 这样做。哪个应该返回所有帖子。 但我收到了这个错误。
我的控制器是这样的
router.get("/all", async (req, res, next) => {
await postModel
.aggregate([
{
$lookup: {
from: "media",
localField: "media",
foriegnField: "_id",
as: "media",
},
},
{ $unwind: "$media" },
{
$addFields: {
totalLikes: { $size: "$likes" },
totalComments: { $size: "$comments" },
},
},
{
$project: {
likes: 0,
comments: 0,
},
},
])
.then((allPosts) => {
res.status(200).send(allPosts);
});
})
在浏览器中没有 $lookup 的输出看起来像这样
【问题讨论】:
标签: node.js mongodb mongoose aggregate