2012-04-18 256 views
2

我正在慢慢發瘋,試圖瞭解如何更新貓鼬中的嵌入式文檔的值,並編寫了一些演示該問題的node.js代碼。運行此嵌入式文檔的貓鼬更新


var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

mongoose.connect('mongodb://localhost/mongoose_broken'); 

var ASchema = new Schema({ 
    value : { type: String, index: { unique: true } }, 
    bs : [BSchema], 
}); 
var BSchema = new Schema({ 
    value : { type: String }, 
}); 
var A = mongoose.model('A', ASchema); 
var B = mongoose.model('B', BSchema); 

// Add an entry of A, with 1 embedded B 
// 
var a = new A(); 
a.value = "hello"; 
var b = new B(); 
b.value = "world"; 
a.bs.push(b); 

a.save(function(err) { 
    if (err) { 
     console.log("Error occured during first save() " + err); 
     return; 
    } 

    // Now update a by changing a value inside the embedded b 
    // 
    A.findOne({ value: 'hello' }, function(err, doc) { 
     if (err) { console.log("Error occured during find() " + err); return; } 

     doc.bs[0].value = "moon"; 

     doc.save(function(err) { 
     if (err) console.log("Error occuring during second save()"); 

     // Check b was updated? 
     // 
     if (doc.bs[0].value != "moon") { 
      console.log ("b was not updated! (first check)"); 
     } else { 
      console.log ("b looks like it was updated (first check)"); 

      // Do a fresh find 
      // 
      A.findOne({value: "hello"}, function(err, doc_2) { 
       if (err) { console.log("Error occured during second find() " + err); return; } 

       if (doc_2.bs[0].value != "moon") { 
        console.log ("b was not updated! (second check)"); 
       } else { 
        console.log ("b looks like it was updated (second check)"); 
       } 
      }); 
     } 
     }); 
    }); 
}); 

輸出是:


b looks like it was updated (first check) 
b was not updated! (second check) 

任何想法,爲什麼嵌入文檔的更新不會保存?

+1

如果你'的console.log(doc_2.bs);'它說什麼了約doc_2 – Menztrual 2012-04-18 13:45:37

+0

的console.log(doc_2.bs)打印 「[Object對象]」 和執行console.log(doc_2 .bs [0])給出了「{value:'world',_id:4f8ee35f8228240f43000002}」 – 2012-04-18 15:54:06

回答

3

在父母中使用它之前,您必須聲明子模式。

var BSchema = new Schema({ 
    value : { type: String }, 
});  
var ASchema = new Schema({ 
    value : { type: String, index: { unique: true } }, 
    bs : [BSchema], 
}); 
+0

你明白了 - 修正了它。我會建議它的一個錯誤,因爲如果你引用一個不存在的模式,你會得到一個錯誤,但不是當它們出現錯誤時......非常意外!無論如何,我今晚可以輕鬆地睡覺,知道這是解決 - 謝謝亞倫:) – 2012-04-18 19:24:09

+0

它的js東西叫「提升」http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Histing – aaronheckmann 2012-04-19 01:15:07