这是一个mongodb官方node.js客户端里的例子
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
// Custom factory (need to provide a 12 byte array);
CustomPKFactory = function() {}
CustomPKFactory.prototype = new Object();
CustomPKFactory.createPk = function() {
return new ObjectID("aaaaaaaaaaaa");
}
MongoClient.connect('mongodb://127.0.0.1:27017/test', {'pkFactory':CustomPKFactory}, function(err, db) {
if(err) throw err;
db.dropDatabase(function(err, done) {
db.createCollection('test_custom_key', function(err, collection) {
collection.insert({'a':1}, function(err, docs) {
collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}).toArray(function(err, items) {
console.dir(items);
// Let's close the db
db.close();
});
});
});
});
});
实际上在node.js里,这种例子比比皆是,因为它的特点就是事件回调,在处理高并发而且逻辑不复杂的代码时,当然是ok的。但是如果我要用它来做应用比较复杂的事情,比如上面这个,一个页面要读取一堆数据,需要我一个一个嵌套写下来简直太痛苦了,不知道node.js里有没有成熟的解决方案呢,兼顾性能和可读性。