更新:我现在知道问题所在了。这是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;
}
});
}
感谢您帮助我调试。
最佳答案
写mongoose.model("Foo").save(cb)
是错误的。
您需要一个有效的模型来使用您定义的架构 "Foo"
, var Foo = new mongoose.model('Foo', FooSchema)
.
然后您需要创建模型 Foo
的实例像这样var test = new Foo({creator:'test'})
之后您才可以调用 .save()
在实例上test
.
关于javascript - 无法在 Mongoose 回调中保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33107739/