簡體   English   中英

在 MongoDB 中顯示來自另一個集合的數據

[英]Display data from another collection in MongoDB

我在 MongoDB 1-> 帖子,2​​-> 評論中有兩個單獨的集合。

后模式:

const postSchema = new mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    media: {
      type: [mongoose.Schema.Types.Mixed],
      trim: true,
      required: true,
    },
    text: String,
    mentions: {
      type: Array,
      default: [],
    },
    hashTags: {
      type: ["String"],
    },
    likes: {
      type: Array,
      default: [],
    },
    postStatus: {
      type: "String",
      default: "public",
      enum: ["public", "private"],
    },
    deletedAt: {
      type: "Date",
      default: null,
    },
  },
  { timestamps: true }
);

評論架構:

const commentSchema = new mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    postId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Post",
      required: true,
    },
    commentText: String,
  },
  { timestamps: true }
);

現在我想顯示請求帖子的所有評論。 帖子表沒有任何鏈接到評論的東西,這就是我不能使用 populate() 的原因。 但評論表有 postId 連接。

這是我嘗試過的:

exports.getPostById = async (req, res) => {
  try {
    let post = await Post.findById(req.params.id);
    if (!post) return res.status(404).json({ message: "No Post found" });
    let comment = await Comment.find({ postId: { $in: {post: req.params.id} } });//Wrong query
    return res.status(200).send(post);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

嘗試這個:

  • 將 id 字符串從 params 轉換為ObjectId
let postObjectId = mongoose.Types.ObjectId(req.params.id);
  • 使用上面定義的變量進行查詢:
let comments = await Comment.find({ postId: postObjectId});

在聚合查詢中使用查找。 請參考此鏈接。

https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/

例如:db.post.aggregate([{ $lookup: { From: 'comment', LocalField: 'user_id', foreignField: 'user_id', as: 'whatever_name_you_want' }}]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM