Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 猫鼬拯救一对多_Javascript_Node.js_Mongodb_Mongoose - Fatal编程技术网

Javascript 猫鼬拯救一对多

Javascript 猫鼬拯救一对多,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我在mongoose有以下模式,其中博客有很多评论 var mongoose = require('mongoose') , Schema = mongoose.Schema var blogScheam = Schema({ title: String, comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }] }); module.exports

我在mongoose有以下模式,其中博客有很多评论

   var mongoose = require('mongoose')

        , Schema = mongoose.Schema

    var blogScheam = Schema({
        title: String,
        comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]
    });

    module.exports = mongoose.model('Post', blogScheam);
注释模型

var mongoose = require('mongoose')

    , Schema = mongoose.Schema

var commentSchema = Schema({
    comment: String,
    user: { type: Schema.Types.ObjectId, ref: 'User' }
});


module.exports = mongoose.model('Comment', commentSchema);
用户模式

var mongoose = require('mongoose')

    , Schema = mongoose.Schema

var userScheam = Schema({
    name: String,
    age: Number,
    posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
});


module.exports = mongoose.model('User', userScheam);
我正在使用以下功能保存相关博客帖子中的评论。我可以保存评论,但是评论被保存为嵌入文档,而我希望博客应该只有_id

app.post('/comment', (req, res) => {
    Blog.findById({ _id: req.body._id }).then(blog => {
        var comment = new Comment({
            comment: req.body.title
        })

        blog.comments.push(comment2);
        blog.save().then(() => {
            res.render("details");
        }).catch(() => {
            res.render("details");
        })
    });
});

由于博客架构希望注释字段仅包含注释id数组,因此您需要先保存注释,然后将新注释id推送到博客:

app.post('/comment', (req, res) => {
    const comment = new Comment({
        comment: req.body.title
    });

    comment.save().then(c => (
        Blog.findByIdAndUpdate(req.body._id,{ '$push': { 'comments': c._id } });
    )).then(() => {
        res.render("details");
    }).catch(() => {
        res.render("details");
    });
});