【问题标题】:Need to do a many comments belong to one article relation MongoDB需要做很多评论属于一篇文章关系MongoDB
【发布时间】:2017-02-19 21:05:32
【问题描述】:

我正在使用 Mongoose/MongoDB,我试图将许多 cmets 与一篇文章相关联。我的应用程序首先从网站抓取,然后用户可以选择保存抓取到 MongoDB 的每篇文章。当用户选择保存一篇文章时,我将其保存到数据库中。因此,当用户点击他们保存的一篇文章时,他们可以对其发表评论。每篇文章都有自己的评论部分,我需要检索正确的 cmets。

//我在JS文件中的发表评论请求

function postComment(){

    var articleComment = {
        comment: $('#comment').val().trim()
    }

    $.post('/comments/' + articleID, articleComment).done(function(data){
        $('.main-popup').fadeOut();
        console.log('DONNE', data);
    });
}

//在控制器中发布路由

router.post('/comments/:id', function(req, res){

    var newComment = new Comment(req.body);

    newComment.save(function(err, doc){
        if(err){
            console.log(err);
        }else{
            Comment.findOneAndUpdate({ "_id": doc._id }, { "article": req.params.id }).exec(function(err, doc){
                if(err){
                    console.log(err);
                    res.send(err);
                }else{
                    res.send(doc);
                }
            });
        }
    });

});

//点击特定文章时获取获取正确cmets的请求

function showCommentBox(){

    $('.comments').empty();
    $('#comment').val("");
    articleID = $(this).attr('data-article-id');

    $.get('/comments/' + articleID, function(data){


        if(data.article){ //This is undefined*********************
            for(var x = 0; x < data.comment.length; x++){

                $('.comments').append("<div><h2>" + data.comment[x].comment + "</h2><span><button>&times;</button></span></div>");
            }
        }
        $('.main-popup').fadeIn();
    });


}

//获取控制器中的路由

router.get('/comments/:id', function(req, res){
    Comment.findOne({ "article": req.params.id }).populate("article").exec(function(err, doc){

        if(err){
            console.log(err)
        }else{
            res.json(doc);
        }
    }); 
});

//文章模型

var mongoose = require('mongoose');
var Schema = mongoose.Schema;


var ArticleSchema = new Schema({

    title: {
        type: String
    },
    link: {
        type: String
    },
    description: {
        type: String
    },
    img: {
        type: String
    }
});

var Article = mongoose.model("Article", ArticleSchema);

module.exports = Article;

//评论模型

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var CommentSchema = new Schema({

    comment: {
        type: String
    },
    article: {
        type: Schema.Types.ObjectId,
        ref: 'Article'
    }

});


var Comment = mongoose.model('Comment', CommentSchema);
module.exports = Comment;

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    首先,您在执行 .findOneAndUpdate 时缺少 $set。另外我认为您应该在设置之前将字符串转换为 Mongo ObjectId。 所以它可能看起来像这样:

    const ObjectId = mongoose.Types.ObjectId;
    
    Comment.findOneAndUpdate({ "_id": doc._id }, {$set: {"article": new ObjectId(req.params.id) }})

    您也不需要进行 2 次数据库调用。您可以在保存 newComment 之前添加文章 id,然后简单地将其作为响应发送,如下所示:

    //Please notice that mongoose.Schema.Types.ObjectId and mongoose.Types.Object are different types.
    //You need this one here:
    const ObjectId = mongoose.Types.ObjectId;
    
    router.post('/comments/:id', function(req, res){
    	var newComment = new Comment(req.body);
    	newComment.article = new ObjectId(req.params.id);
    
    	newComment.save(function(err, doc){
    		if (err) {
    			console.error(err);
    			res.send(err);
    
    			return;
    		}
    
    		res.send(doc);
    	});
    });

    【讨论】:

    • 好的,谢谢您的意见。但是,我认为我需要两次调用数据库。当用户单击 cmets 按钮时,这会使我的 cmets 模态显示。我的评论模式中的提交按钮是发布请求的原因。
    • @ANonymous 我一直在谈论不同的事情。您在 POST 端点内进行了 2 个调用而不是 1 个调用。 1) .save 到 mongo 2) .findOneInUpdate 到 mongo 并修改同一个文档。这应该在一次调用中完成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 2012-01-24
    • 2017-04-10
    • 1970-01-01
    相关资源
    最近更新 更多