猫鼬子文档数组更改值

时间:2018-11-22 16:31:04

标签: node.js mongodb mongoose mongodb-query

我收到一个猫鼬查询,我想在其中更改评论。我从React应用收到了commentid。但这不起作用,可能是什么问题?

后面是示例注释数组

"comments": [       
    {
        "createdAt": "2018-11-22T08:28:36.881Z",            
        "_id": "5bf668b4001de72dc089c849",     // commentid       
        "comment": "111111111111",            
        "username": "kohahn21"        
    }, 
    ....
]

我尝试过的事情:

edit = await Post.update(
    { 'comments._id' : commentid },
    { '$set' : { 'comments.$.comment' : comment  } }, 
    { new: true }
);

ctx.body = edit;

ctx.body

{
    "n": 1,
    "nModified": 1,
    "ok": 1
}

发布架构

const Comment = new Schema({
    createdAt: { type: Date, default: Date.now },
    username: String, 
    comment: String
});

const Post = new Schema({
    username: String,    
    comments: { 
        type: [Comment],
        default: []
    },

});

module.exports = mongoose.model('Post',Post);

我想接收评论,这是修改后的评论布局。我该怎么办?

1 个答案:

答案 0 :(得分:0)

您的语法看起来正确。但是应该是“评论”而不是“项目”。

尝试Post.update( { 'comments._id' : commentid }, {'$set' : { 'comments.$.comment' : comment } });

btw新标志仅适用于查找和运算符。

相关问题