更新嵌套数组的字段

时间:2017-11-14 18:28:39

标签: javascript mongodb mongoose

我有一个架构

const RoomSchema = mongoose.Schema({
title: {
    type: String,
    required: true
},
body: {
    type: String,
    required: true
},
author: {
    type: String,
    required: true
},
resource: {
    type: String
},
posts: {
    type: Array,
    default: []
},
url: {
    type: String
},
created_at: {
    type: String,
    required: true
}});

字段'帖子'是我的数据库中的另一个文档,由以下模式定义:

const PostSchema = mongoose.Schema({
header: {
    type: String,
    required: true
},
body: {
    type: String,
    required: true
},
author: {
   username: {type:String, required: true},
   _id: {type:String, required:true}
},
room: {
    type: String,
    required: true
}});

所以,我试图创建一个查询来更新房间内帖子数组内某些帖子的字段。我已经尝试过这里的建议,但没有结果。我很感激有关该主题的任何帮助

 Room.update({ '_id': roomId, 'posts._id': postId },
    { $set: { 'posts.$.header': newHeader, 'posts.$.body': newBody } },
    callback);

0 个答案:

没有答案