如何将对象推入深度嵌入文档中包含的数组?

时间:2014-07-02 00:47:44

标签: node.js mongodb mongoose mongodb-query

我正在尝试将新对象推送到嵌入文档中包含的数组。不知怎的,我没有完全正确的代码。这是我尝试过的:

型号:

var subCommentSchema = mongoose.Schema({
    user : String,
    title : String,
    sub_comment : String,
    created : {
        type: Date,
        default: Date.now
    }
});

var commentSchema = mongoose.Schema({
    user : String,
    title : String,
    comment : String,
    created : {
        type: Date,
        default: Date.now
    },
    sub_comments : [subCommentSchema]
});

var postSchema = mongoose.Schema({
    user : String,
    title : String,
    post : String,
    created : {
        type: Date,
        default: Date.now
    },
    comments : [commentSchema]
});

API调用:

app.post('/comment/:comment_id/sub-comment', function(req, res) {
    var updateData = {
        sub_comments: {
            title: req.body.title,
            sub_comment: req.body.sub_comment,
            user: req.user._id 
        }
    };
    Post.update(
        { "comments._id" : req.params.comment_id }, 
        { $push : updateData }, 
        function(err,data) {
            return res.json(data);
        }
    );
});

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您在更新部分的positional $运算符上缺少匹配项。您还需要一个“点符号”形式的密钥,以便识别您在顶层推送的“评论”字段:

app.post('/comment/:comment_id/sub-comment', function(req, res) {
    var updateData = {
        "comments.$.sub_comments": {
            title: req.body.title,
            sub_comment: req.body.sub_comment,
            user: req.user._id 
        }
    };
    Post.update(
        { "comments._id" : req.params.comment_id }, 
        { $push : updateData }, 
        function(err,data) {
            return res.json(data);
        }
    );
});

匹配查询中提供的_id的“comments”数组的索引,并将文档“推”到该位置的“sub_comments”数组中。