【问题标题】:$Lookup Foriegn Field Mongoose: Unknown Argument$Lookup Foriegn Field Mongoose:未知参数
【发布时间】: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


    【解决方案1】:

    您的键名foriegnField 有拼写错误。

    $lookup: {
       from: "media",
       localField: "media",
       foreignField: "_id",
       as: "media",
    },
    

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 2021-08-23
      • 2020-11-02
      • 2018-08-16
      • 2020-06-10
      • 2020-09-14
      • 2021-08-25
      • 1970-01-01
      • 2020-10-14
      相关资源
      最近更新 更多