javascript - 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.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");
    });
});

关于javascript - Mongoose 保存一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48049466/

相关文章:

javascript - 我无法使用 JavaScript 来播放图像幻灯片

javascript - 组合我的收藏中唯一的两个字段

linux - 远程连接到在 Linux 服务器上运行的 MongoDB

node.js - 如何在 nodeJs 服务器上正确使用 Forest Admin? (与森林 express Mongoose )

javascript - HTML5 游戏引擎 - JavaScript 动画

javascript - 如何使用 if 语句启用按钮?

javascript - 如何知道调用脚本的目录?

node.js - nodejs加密解密有什么问题?

javascript - handlebars.js 中缺少(或 "optional")表达式?

javascript - 测试无法使用 Karma、Browserify、Angular 运行