簡體   English   中英

如何使用MongoDB和Node.js將一個Schema傳遞到另一個Schema

[英]How to pass one Schema into another using MongoDB & Node.js

我試圖在博客文章中發表評論,並將這些評論作為每個帖子的數組。

我已設法將評論發布,但我無法從帖子中調用此信息。 注釋模型中包含文本和作者,但注釋僅占用模型的作者部分。 當評論顯示在帖子上時,它們僅顯示已撰寫評論的用戶的姓名。 我已經檢查了數據庫,並且comment.text根本沒有通過。

注釋創建路線

router.post("/", ensureAuthenticated, (req, res) => {
    Blog.findById(req.params.id, (err, blog) => {
    if(err){
        console.log(err);
        res.redirect("/blog");
    } else {
        Comment.create(req.body.comment, (err, comment) => {
        if(err){
            req.flash("error", "Something went wrong");
            console.log(err);
        } else {
            //add username and id to comment
            comment.author.id = req.user._id;
            comment.author.name = req.user.name;
            comment.author.email = req.user.email;
            comment.save();
            //save comment
            blog.comments.push(comment);
            blog.save();
            req.flash("success", "Successfully added comment");
                    res.redirect("/blog/" + blog._id);
            }
        });
    }
    });
});

評論架構

const mongoose = require("mongoose");
var commentSchema = new mongoose.Schema({
    text: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        name: String,
        email: String
        }
});
module.exports = mongoose.model("Comment", commentSchema);

顯示評論的顯示頁面的一部分

<div class="card-body">
<% blog.comments.forEach(function(comment){ %>
    <div class="row">
        <div class="col-md-12">
        <strong><%= comment.author.name %></strong>
        <span class="float-right">10 days ago</span>
            <p class="card-text">
                <%= comment.text %>
                </p>
        <% if(user && comment.author.id.equals(user._id)) { %>
        <a class="btn btn-warning btn-sm d-inline-block" href="/blog/<%= blog._id %>/comments/<%= comment._id%>/edit">Edit</a>
        <form class="d-inline-block" action="/blog/<%= blog._id %>/comments/<%= comment._id%>?_method=DELETE" method="POST">
        <button class="btn btn-danger btn-sm">Delete</button>
        </form>
<% } %>
<hr>
    </div>
    </div>
<% }) %>
</div>

我期待展示頁面顯示每條評論的文字。

我缺少bodyParser。 如果其他人有這個問題, https: //stackoverflow.com/a/55793723/8145657為我修復了它。

暫無
暫無

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

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