2011-05-25 127 views
0

我想要做的事情應該是直截了當的,但由於某種原因,我很難理解這一點。我有以下Mongoose模式(簡化)。如何使用Mongoose將嵌入式文檔從一個文檔放入另一個文檔?

var Status = new Schema({ 
    name : { type: String, required: true }, 
    description : { type: String } 
}); 

var Category = new Schema({ 
    statuses : [Status], // contains a list of all available statuses 
    // some other attributes 
}); 

var Book = new Schema({ 
    statuses : [Status], // preferably this would not be an array but a single document, but Mongoose doesn't seem to support that 
    // some other attributes 
}); 

現在,我要做到以下幾點:

  1. 檢索類別文檔
  2. 查找特定的嵌入式狀態文件(根據要求PARAM)
  3. 分配一個特定的嵌入式狀態文件到一個特定的書籍文件。我想要替換現有的圖書狀態,因爲在任何時候,應該只有一本書的狀態。

這是目前我在做什麼:

mongoose.model('Category').findOne({_id: id}, function(err, category){ 
    if(err) next(err); 
    var status = category.statuses.id(statusId); // statusId available via closure 
    book.statuses[0] = status; // book available via closure; trying to replace the existing status here. 
    book.save(function(err){ 
     if(err) next(err); 
     next(); 
    }); 
}); 

上面看上去一切正常,我沒有得到任何錯誤。但是,新狀態不會保存到文檔中。下次我輸出更​​新的Book文檔時,它仍然具有舊的狀態。我調試了這個和find()方法以及設置狀態似乎沒有問題。

我現在唯一能想到的是,我分配的狀態值不是以正確的格式保存在Mongoose中。儘管如此,我仍然期待某種錯誤消息。

或者也許有更好的方法來做到這一切嗎?

回答

0

這可能是因爲您正在嘗試複製嵌入文檔,該文檔本身可能具有與其關聯的ObjectId。試圖在Book內保存重複的Status會創建兩個嵌入文檔,其編號與ObjectId相同。嘗試創建一個新的狀態對象並複製這些字段。

對於嵌入式文檔,很難在ObjectsId上找到文檔,但在此提及它們:http://mongoosejs.com/docs/embedded-documents.html

相關問題