簡體   English   中英

Mongoose 使用方法將模式添加到模式中

[英]Mongoose add schema into schema using method

我正在嘗試使用 Mongo DB 構建一個使用 Node.js 作為服務器端語言的博客。

因此,在我的博客中,人們可以像其他博客一樣撰寫帖子並向帖子添加評論。

每個帖子都會有評論,這就是我正在嘗試使用我的帖子模式。 當有人嘗試對帖子發表評論時,它會向服務器發送 POST 請求,創建新評論並將其保存到數據庫中。

當我測試時,評論本身會被正確保存,但是我在將它附加到 post schema 時遇到了問題。

這是我的 postSchema.js:

const mongoose = require("mongoose");

const postSchema = new mongoose.Schema(
  {
    owner: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true
    },
    title: {
      type: String,
      required: true
    },
    body: {
      type: String,
      required: true
    },
    comments: [
      {
        comment: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "Comment"
        }
      }
    ]
  }
);

還有我的 commentSchema.js:

const mongoose = require("mongoose");

const commentSchema = new mongoose.Schema(
  {
    owner: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true
    },
    post: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Post",
      required: true
    },
    content: {
      type: String,
      required: true
    }
  }
);

module.exports = Comment = mongoose.model("Comment", commentSchema);

所以帖子模式有評論數組來存儲評論。 每次用戶添加評論時,它都會創建一個 POST 請求:

router.post("/:id/new_comment", async (req, res) => {
  const { content } = req.body;
  const comment = new Comment({
    content,
    owner: req.user._id,
    post: req.params.id
  });
  try {
    const post = await Post.findOne({ _id: req.params.id });
    await comment.save();
    await post.addComment(comment);
    res.status(201).send({ post, comment });
  } catch (error) {
    res.status(500).send({ error: error.message });
  }
});

所以這個 POST 請求會尋找帖子添加評論,保存評論,然后調用 addComment() 將評論連接到帖子的 comments 數組中。 此處創建的注釋將用作 addComment() 函數的參數。

addComment() 函數位於 PostSchema.js 文件中,它是:

postSchema.methods.addComment = async function(comment) {
  const post = this;
  post.comments = post.comments.concat({ comment });
  await post.save();
  return post;
};

一切正常,但結果與我預期的不同。 我希望它像

{
    "post": {
        "_id": "5e2e94c9e6ef8100ecfaf665",
        "title": "Test Post",
        "body": "Test Body",
        "owner": "5e2e6bbd18929829e8679cec",
        "comments": [
            {
                "_id": "5e2e98d9587c78444cd600b2",
                "comment": {
                    "_id": "5e2e98d9587c78444cd600b1",
                    "content": "Test Comment",
                    "owner": "5e2e6bbd18929829e8679cec",
                    "post": "5e2e94c9e6ef8100ecfaf665",
                    "__v": 0
                }
            }
        ],
    },
    "comment": {
        "_id": "5e2e98d9587c78444cd600b1",
        "content": "Test Comment",
        "owner": "5e2e6bbd18929829e8679cec",
        "post": "5e2e94c9e6ef8100ecfaf665",
        "__v": 0
    }
}

第一條看起來不錯,但是當我嘗試保存第二條評論時問題就出現了。 以某種方式更改之前保存的評論,如下所示:

{
    "post": {
        "_id": "5e2e94c9e6ef8100ecfaf665",
        "title": "Test Post",
        "body": "Test Body",
        "owner": "5e2e6bbd18929829e8679cec",
        "comments": [
            {
                "_id": "5e2e98d9587c78444cd600b2",
                "comment": "5e2e98d9587c78444cd600b1"
            },
            {
                "_id": "5e2e98d9587c78444cd600b3",
                "comment": {
                    "_id": "5e2e98d9587c78444cd600b2",
                    "content": "Test Comment 2",
                    "owner": "5e2e6bbd18929829e8679cec",
                    "post": "5e2e94c9e6ef8100ecfaf665",
                    "__v": 0
                }
            }
        ],
    },
    "comment": {
        "_id": "5e2e98d9587c78444cd600b2",
        "content": "Test Comment 2",
        "owner": "5e2e6bbd18929829e8679cec",
        "post": "5e2e94c9e6ef8100ecfaf665",
        "createdAt": "2020-01-27T08:01:29.492Z",
        "updatedAt": "2020-01-27T08:01:29.492Z",
        "__v": 0
    }
}

當我創建測試評論 2 時,我保存的第一個評論發生了變化。 什么可能導致這種情況? 感謝您閱讀這么長的問題。 任何幫助將不勝感激! 祝你今天過得愉快。

問題是你正在傳遞完整的評論而不是它的 id。

  await post.addComment(comment_id); // pass comment id here 

因為在你的帖子模型中

comments: [
      {
        comment: {
          type: mongoose.Schema.Types.ObjectId, // you are storing ObjectId here 
          ref: "Comment"
        }
      }
    ]

因此,您可以將您的評論存儲為您的評論 id 數組,然后您可以在想要填充它時獲得完整的評論

暫無
暫無

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

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