【发布时间】:2016-01-11 12:04:37
【问题描述】:
更新:我现在知道问题所在了。这是follow-up question。
我正在使用 Mongoose 和 MongoDB 的 MMEAN 堆栈。我在save() 上收到TypeError: undefined is not a function 错误,因为我试图在回调中使用 Mongoose 保存到 MongoDB。不知道如何正确保存。
这是我必须遵循的逻辑:
- 检查 Foo 集合是否为空
- 如果 Foo 为空,则保存新的 Foo 文档
- 如果 Foo 不为空,则不要保存新的 Foo 文档
我相信除了有问题的mongoose.model("Foo").save(cb); 行之外的其余代码都没有错误。但以防万一,我已将所有内容都包含在这里。我正在从 routes/index.js 调用保存方法 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;
}
});
}
感谢您帮我调试。
【问题讨论】:
标签: javascript node.js mongodb mongoose mean-stack