2016-09-18 124 views
0

我在MongooseJS以下模式:推到嵌套subdoc的陣列MongooseJS

const ParentChildCommentSchema = new mongoose.Schema({ 
    date: Date, 
    from: { type:mongoose.Schema.Types.ObjectId, ref:'Parent' }, 
    message: String, 
}); 

const ParentChildSchema = new mongoose.Schema({ 
    child: { type:mongoose.Schema.Types.ObjectId, ref:'Child' }, 
    comments: [ ParentChildCommentSchema ], 
}); 

const ParentSchema = new mongoose.Schema({ 
    name: String, 
    description: String, 
    children: [ ParentChildSchema ], 
}); 

ParentsChildren,並且每個父/子關係可以具有comments陣列。

我試圖推comment

const query = { 
    "_id": parentId, 
    "children._id": parentChildId, 
}; 

const update = { 
    "$push": { 
    "children.$.comments": { 
     "date": Date.now(), 
     "from": parentId, 
     "message": message, 
    } 
    } 
}; 

Pack.findOneAndUpdate(query, update, err => ...) 

查詢不拋出任何錯誤。但沒有評論被添加。我究竟做錯了什麼?

+1

不知道這是否會帶來很大的不同,但將''$ push''改爲'$ push' – Derek

+0

我不認爲這有什麼區別。我有一個幾乎相同的查詢,$ set是ParentChildSchema中的一個值,它工作正常,用引號括起來。 – nicholas

+0

經過測試,但沒有運氣。仍然成功完成,但不會推入陣列。 – nicholas

回答

1

原來問題出在路由器上 - 沒有通過ParentChild id - 因此上面的代碼是正確的並且正常工作。