简体   繁体   English

猫鼬和node.js,填充并保存在数据库中?

[英]Mongoose and node.js, populating and saving in database?

Those are my two schematics for discussions and replies: 这些是我的两个示意图,用于讨论和回复:

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;

This is in my controller: 这是在我的控制器中:

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);

    }

I am trying to get the logged in user and his reply (as string) and to save it in mongoose database, so I can show it under the current discussion. 我正在尝试获取登录的用户及其答复(作为字符串),并将其保存在mongoose数据库中,因此我可以在当前讨论中进行展示。

That's how the database is right now: 现在数据库就是这样的:

"reply": [], “回复”:[],

Any ideas how I can do this? 有什么想法可以做到吗?

So the issue isn't in the code you've posted here. 因此,问题不在您在此处发布的代码中。 The problem starts in details.hbs the POST is missing the 'discussion' object for id. 问题始于details.hbs POST缺少id的“讨论”对象。

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

The next issue I found is that the user object isn't being populated on the Discussion detail. 我发现的下一个问题是没有在“讨论”详细信息上填充用户对象。 I update the detail controller to use: 我更新了细节控制器以使用:

  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})
        });

    },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM