我已经阅读了这些内容,但是在执行它时遇到了一些麻烦。 mongoDB 承诺过早返回
具体来说,我试图承诺 collection.find 光标,但我不确定我做对了......任何帮助将不胜感激:
//mongo.js
var promise = require('bluebird');
var mongodb = require('mongodb');
var mongoClient = mongodb.MongoClient;
var collection = mongodb.Collection;
promise.promisifyAll(mongodb);
promise.promisifyAll(collection.prototype);
collection.prototype._find = collection.prototype.find;
collection.prototype.find = function() {
var cursor = this._find.apply(this, arguments);
cursor.toArrayAsync = promise.promisify(cursor.toArray, cursor);
return cursor;
};
var myfunction = function(callback){
// configure and export database (async)
mongoClient.connectAsync(database)
.then(function(db){
module.exports.db = db;
promise.all([
db.createCollectionAsync('hoth', {w:1})
.then(function(collection){
module.exports.hoth = collection;
collection.ensureIndexAsync({time:-1, location:'2dsphere'})
.done(function(index){console.log(index+' hoth');});
}),
db.createCollectionAsync('endor', {w:1})
.then(function(collection){
module.exports.endor = collection;
collection.ensureIndexAsync({time:-1, location:'2dsphere'})
.done(function(index){console.log(index+' endor');});
}),
db.createCollectionAsync('alderaan', {w:1})
.then(function(collection){
module.exports.alderaan = collection;
collection.ensureIndexAsync({time:-1, location:'2dsphere'})
.done(function(index){console.log(index+' alderaan');});
})
])
.done(function(){callback(null);});
});
};
module.exports.myfunctionAsync = promise.promisify(myfunction);
这是 app.js
// app.js
mongo.myfunctionAsync()
.then(function(result){
mongo.hoth.mapReduceAsync(u.map, u.reduce,{
out: {replace:'deathstar'}, scope:{size:0.01},
query: {time:{$gte:ago}}, finalize:u.finalize});
}).then(function(deathstar){
deathstar.findAsync({},{fields:{_id:0, value:1}});
}).then(function(docs){
var final = _.map(docs, function(doc){return doc.value;});
}).then(function(final){
mongo.alderaan.insertAsync(final, {w:1});
}).then(console.log('done'));
这是错误
Cannot call method 'findAsync' of undefined