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