【发布时间】:2012-09-13 21:26:28
【问题描述】:
我不清楚如何使用该连接和查询集合。 因为有时连接已经存在并且没有问题。但是当需要建立连接时,集合查询不会排队。 你也不能一直建立新的联系,因为你可以(而且应该)只建立一个。 似乎您需要在连接回调中使用集合查询,但在连接已经存在时也需要独立。
当然,这是不可撤消的,但是由于开销很大,我想我做得不对。 毕竟,这对我来说似乎有点句法糖精。 syntactic sugar 在哪里?
这是一个基本的例子。想象一下在同一秒内有一堆请求:
var util = require('util'),
mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db,
mServer = new Server('localhost', 27017),
mDb = new Db('SomeDatabase', mServer),
db;
if (mDb._state == 'disconnected') {
util.debug('MONGODB: connecting...');
mDb.open(function(err, newDb) {
if (!err) {
db = newDb;
// I cannot immediately work on a collection here,
// because it takes a moment for the db to connect.
}
});
}
else if (mDb._state == 'connecting') {
// I need to catch this state because I cannot work on collections yet,
// but I cannot connect either because it's already connecting.
}
// else if (mDb._state == 'connected') {
// Queries need to be performed after connection is established
// or when connection was already established by a previous request.
db.createCollection(collection, function(err, collection) {
if (!err) {
collection.insert(record, {safe:true}, function(err, result) {
util.debug('MONGODB: Inserted.');
});
}
});
// }
现在,我找到的初学者指南都是关于 mDb.open 上的回调,但是当节点已经运行时,这会给后续请求带来问题。它拒绝打开另一个连接。 那么,当单个启动回调还不够时,真正在 nodejs 中使用 mongodb 的正确方法是什么?
我想象一个你以回调形式传递查询的模块,它为你传递回调,或者(1)到它等待连接回调的地方,(2)直接到集合,或者(3)等待连接,但连接回调为时已晚。但就像我说的,这是纯粹的句法糖精。
【问题讨论】:
-
听起来你想要一个 Deferred 对象用于你的数据库连接...
标签: javascript node.js mongodb