我正在使用包含 Mongoose 和 MongoDB 的 MMEAN 堆栈。我想测试集合 Foo 是否为空,但它涉及 Mongoose find()
带有回调的函数。 我不熟悉回调,所以我想知道如何从回调内部获取一条信息到其父函数中。
这是我必须遵循的 addFoo 逻辑: 1.检查Foo集合是否为空 2.如果Foo为空,则保存新的Foo文档 3.如果Foo不为空,则不保存新的Foo文档
我正在调用保存方法,addFoo()
,来自routes/index.js。
// routes/index.js
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
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){
// HOW DO I LET addFOO() KNOW THAT THE ARRAY IS EMPTY?
// somehow pass the boolean out to addFoo()
}
});
// IF Empty
// this.save(cb);
}
最佳答案
这将按如下方式工作......
FooSchema.methods.addFoo = function(cb){
var that = this;
this.model("Foo").find(function(err, results){
if (err){return err;}
// if the Foo results array is empty
if (results.length == 0){
that.save(cb);
}
});
}
但是,如果您想根据实际需求将其传递给父级,那么您可以尝试如下......
FooSchema.methods.addFoo = function(cb){
var that = this;
this.model("Foo").find(function(err, results){
if (err){return err;}
// if the Foo results array is empty
that.commit(!results.length);//Calling a parent function from inside callback function
});
function commit(doCommit){
if(doCommit) {
that.save(cb);
}
}
}
关于javascript - 如何将内部回调的结果传递到其父函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33114479/