我已经阅读了这些,但我在执行它时遇到了一些麻烦。 mongoDB promise gets returned too early
具体来说,我试图宣传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
答案 0 :(得分:4)
使用bluebird 2.0,您可以宣传npm。之后光标也被宣传了。
以下是光标的一般示例:
var MongoClient = require('bluebird').promisifyAll(require("mongodb")).MongoClient;
然后:
MongoClient.connectAsync("mongodb://localhost:27017/something")
.then(function(db) {
db.collection('foo').findAsync({ })
.then(function(cursor) {
return cursor.toArrayAsync();
})
.then(function(arrayOfFoos) {
console.log(arrayOfFoos);
});
});