Mongoose和node.js,在数据库中填充和保存?

时间:2017-04-12 19:28:52

标签: javascript node.js mongoose

这是我讨论和回复的两个原理图:

Source code for the two schematics

const mongoose = require('mongoose');
const ObjectID = mongoose.Schema.Types.ObjectId;

let discussionSchema = mongoose.Schema({
    title: {type: String, required: true},
    content: {type: String},
    author: {type: ObjectID, required: true, ref: 'User'},
    date: {type: Date, default: Date.now()},
    reply: [{ type: ObjectID, ref: 'Replying' }]
});

let discussionReplyingSchema = mongoose.Schema({
    content: {type: String, required: true},
    author: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},
    date: {type: Date, default: Date.now()}
});

const Discussion = mongoose.model('Discussion', discussionSchema);
const Replying = mongoose.model('Replying', discussionReplyingSchema);

module.exports = Discussion;
module.exports = Replying;

这是在我的控制器中:

Source code for the controller

replyPost: (req, res) => {
        console.log(req.body);
        let id = req.params.id;
        let replyContent = req.body.replyContent;
        console.log(replyContent);

    }

我正在尝试获取登录用户和他的回复(作为字符串)并将其保存在mongoose数据库中,因此我可以在当前讨论中显示它。

现在的数据库是怎样的:

"回复":[],

我有什么想法可以做到这一点吗?

1 个答案:

答案 0 :(得分:0)

所以问题不在于您在此处发布的代码中。问题始于details.hbs,POST缺少id的“讨论”对象。

<form class="form-horizontal" method="POST" action="/discussion/details/{{discussion.id}}">

我发现的下一个问题是未在讨论详细信息上填充用户对象。我更新了要使用的详细控制器:

  details: (req, res) => {
        let id = req.params.id;

        Discussion.findById(id).populate('author').then(discussion => {
            if (!req.user) {
                res.render('discussion/details', {discussion: discussion, isUserAuthorized: false});
                return;
            }

            let isUserAuthorized = req.user.isAdmin || req.user.isAuthorDiscussion(discussion);
            res.render('discussion/details', {user: req.user, discussion: discussion, isUserAuthorized: isUserAuthorized})
        });

    },