【问题标题】:How to pass one Schema into another using MongoDB & Node.js如何使用 MongoDB 和 Node.js 将一个模式传递到另一个模式
【发布时间】:2019-06-09 23:00:48
【问题描述】:

我正在尝试将 cmets 发布到博客文章中,并将这些 cmets 作为每个帖子的数组。

我已经设法让 cmets 发布,但我无法调用帖子中的信息。评论模型中包含文本和作者,但评论仅包含模型的作者部分。当 cmets 出现在帖子上时,他们只显示写评论的用户的名字。我检查了数据库,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>

我希望显示页面显示每条评论的文本。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    我缺少 bodyParser。万一其他人有这个问题,https://stackoverflow.com/a/55793723/8145657 已经帮我解决了。

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 2014-08-14
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 2021-12-13
      • 2019-06-14
      相关资源
      最近更新 更多