2015-10-13 107 views
0

更新:我現在知道這個問題。這是follow-up question未能保存在貓鼬回調中


我正在與一個MMEAN堆棧與Mongoose和MongoDB。我在save()上遇到了TypeError: undefined is not a function錯誤,因爲我試圖用回調中的Mongoose保存到MongoDB。我不知道如何正確保存它。

這是邏輯我必須遵循:

  1. 檢查如果富集合爲空
  2. 如果foo是空的,保存新富文檔
  3. 如果富不爲空,不救新的Foo文件

我相信其他代碼除了有問題的mongoose.model("Foo").save(cb);行是沒有錯誤的。但爲了以防萬一,我在這裏包括了一切。我正在從routes/index.js調用save方法addFoo()

// routes/index.js - No errors here 
router.post('/foo', function(req, res, next){ 
    var foo = new Foo(req.body); 
    foo.addFoo(function(err, bid){ 
    if(err){ return next(err); } 
    res.json(foo); 
    }); 
}); 

// models/Foo.js - THE ERROR IS IN HERE 

var mongoose = require('mongoose'); 
var FooSchema = new mongoose.Schema({ 
    creator: String 
}); 
mongoose.model('Foo', FooSchema); 

FooSchema.methods.addFoo = function(cb){ 

    // finds all documents of Foo into the "results" array 
    this.model("Foo").find(function(err, results){ 
    if (err){return err;} 

    // if the Foo results array is empty 
    if (results.length == 0){ 

     // THE LINE BELOW IS WHERE THE ERROR OCCURS 
     // mongoose.model("Foo").save(cb); 
     //      ^
     // TypeError: undefined is not a function 
     mongoose.model("Foo").save(cb); 
     return; 
    } 
    }); 
} 

感謝您幫助我調試。

回答

1

寫錯mongoose.model("Foo").save(cb)

您需要一個有效的模型才能使用您定義的模式"Foo",var Foo = new mongoose.model('Foo', FooSchema)

然後,你需要這樣的var test = new Foo({creator:'test'}),只有後,你將能夠調用.save()的實例test創建模型Foo的一個實例。

+0

有沒有辦法將result.length == 0作爲布爾值傳遞給addFoo函數? – Melissa

+0

我對先前的評論有一個跟進問題,請查看:http://stackoverflow.com/q/33114479/4825465 – Melissa