0
更新:我現在知道這個問題。這是follow-up question。未能保存在貓鼬回調中
我正在與一個MMEAN堆棧與Mongoose和MongoDB。我在save()
上遇到了TypeError: undefined is not a function
錯誤,因爲我試圖用回調中的Mongoose保存到MongoDB。我不知道如何正確保存它。
這是邏輯我必須遵循:
- 檢查如果富集合爲空
- 如果foo是空的,保存新富文檔
- 如果富不爲空,不救新的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;
}
});
}
感謝您幫助我調試。
有沒有辦法將result.length == 0作爲布爾值傳遞給addFoo函數? – Melissa
我對先前的評論有一個跟進問題,請查看:http://stackoverflow.com/q/33114479/4825465 – Melissa