2012-03-29 68 views
1

我正嘗試將嵌入文檔添加到現有文檔字段。我發現one fitting answer與搜索,但我遇到了錯誤。我正在使用node.js,Express和Mongoose。將文檔添加到嵌入文檔數組

我的數據庫模式:

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

var compo = new Schema({ 
    name  : String, 
    description : String, 
    entries  : [entry] 
}); 

我試圖更新條目陣列用下面的代碼

var entry = new entryModel(); 
entry.name = "new name"; 
entry.description= "new description"; 

compoModel.findOne(query, function (err, item) { 
    if (item) { 
    item.entries.push(entry); 
    item.save(function (err) { 
     if (!err) { 
     log.debug('Entry added successfully.'); 
     } else { 
     log.error("Mongoose couldn't save entry: " + err); 
     } 
    }); 
    } 
}); 

則產生了一個錯誤:TypeError: Object.keys called on non-object

有什麼我錯過了?

回答

1

所以我設法通過簡單地增加一個新的對象爲compo.entries列表和調用compoModel.update得到它通過Model.update方法工作。

1

通過清除子文檔數組解決了我的類似問題(同樣的錯誤)。它在子文檔方案的定義之前已經被填充。 至少這是我認爲發生的事情。

例如爲:

var token = new Schema({ value: String, expires: Date }) 
var user = new Schema({ username: String, tokens: [token] }) 

..而且,定義 '令牌' 方案之前我有條目,如:

{ username: 'foo', tokens: ['123456'] } 

..所以,清除標記爲我做。

user.tokens = [] 
user.save()