我正在尝试使用mongo-lite从同一个数据库连接访问多个mongo集合。这是一个示例快递应用程序。
var express = require('express') ;
var app = express();
var http = require('http');
var mongolite = require('mongo-lite');
db = mongolite.connect("mongodb://localhost/fnard", ['col1','col2']);
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(request, response){
db.collection('col1').insert({hi:5},function(){});
db.collection('col2').insert({hi:5},function(){});
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
http.createServer(app).listen(3000, function () {
console.log('Express server listening on port ' + '3000');
});
以下是我在/上执行GET的错误:
Error: A Server or ReplSetServers instance cannot be shared across multiple Db instances
但是,如果我使用以下代码,GET会按预期插入文档
var express = require('express') ;
var app = express();
var http = require('http');
var mongolite = require('mongo-lite');
db = mongolite.connect("mongodb://localhost/fnard", ['col1']);
db2 = mongolite.connect("mongodb://localhost/fnard", ['col2']);
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(request, response){
db.collection('col1').insert({hi:5},function(){});
db2.collection('col2').insert({hi:5},function(){});
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
我是否需要为我想要访问的每个集合创建一个新连接? mongo-lite文档似乎表明情况并非如此 - .connect()选项允许您指定要使用的集合,但它似乎不起作用。
答案 0 :(得分:1)
竞争条件正在给你错误。以下适用于我:
var express = require('express');
var app = express();
var http = require('http');
var mongolite = require('mongo-lite');
db = mongolite.connect("mongodb://localhost/fnard", ['col1','col2']);
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(request, response){
db.collection('col1').insert({hi:5},function(){
db.collection('col2').insert({hi:5},function(){
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
});
});
});
http.createServer(app).listen(3000, function () {
console.log('Express server listening on port ' + '3000');
});
您需要嵌套回调。或者,您可以使用async之类的库:
var express = require('express');
var async = require( 'async' );
var app = express();
var http = require('http');
var mongolite = require('mongo-lite');
db = mongolite.connect("mongodb://localhost/fnard", ['col1','col2']);
app.use(express.bodyParser());
app.use(app.router);
app.get('/', function(request, response){
async.series( [
// First insert
function ( callback ) {
db.collection('col1').insert({hi:5},callback);
},
// Second insert
function ( callback ) {
db.collection('col2').insert({hi:5},callback);
}
// Send response
], function ( error, results ) {
console.log(request.body); // your JSON
response.send(request.body); // echo the result back
} );
});
http.createServer(app).listen(3000, function () {
console.log('Express server listening on port ' + '3000');
});