mongo-js / mongojs Goto Github PK
View Code? Open in Web Editor NEWNode.js module that implements the offical mongo api
Home Page: https://mongo-js.github.io/mongojs/
License: MIT License
Node.js module that implements the offical mongo api
Home Page: https://mongo-js.github.io/mongojs/
License: MIT License
Using connection pools would be very handy. I dont see any documentation for it though, so I'll poke around and guess at it.
I get the following error:
[Error: Tailable cursor cannot be converted to array]
When doing this:
db.messages.find({}, { tailable: 1, awaitdata: 1 }, function (err, cursor) {
console.log(err);
});
Going through the client interface directly avoids this problem (but defeats the purpose of using mongojs in the first place).
db.client.collection("messages", function (err, collection) {
collection.find({}, { tailable: 1, awaitdata: 1 }, function (err, cursor) {
console.log("cursor: ", cursor);
});
});
From the readme:
If you provide a callback to find or any cursor config operation mongojs will call toArray for you
So I guess I'm wondering if there is a recommended way to work with tailable cursors via mongojs or if I should continue working around it as above.
I'm using node+mongo+mongojs to parse a large dataset at once and insert the records into monogo. The issue I am running into is that I have no way of throttling my inserts to account for the memory limit of the process.
It appears that repeated calls to insert or save return immediately and continue to push records for insert onto some internal queue that can grow unbounded. Is there are recommended way of throttling this so that I do not blow through all the memory?
The only way I know of to throttle this is to set safe: true and then perform subsequent inserts in the callback. I'm concerned that this might build up a deep call stack and it would force me to push a lot more information into the insert callback than I originally had hoped for. Is this the recommended approach?
I'm new to node so maybe I'm missing something here.
Thanks,
brian
I'm using mognojs version 0.7.2 and socket.io, and works fine but when I don`t make queries to datatabase maybe a timeout close the connection, and after when i try to make any query the callback error respond [Error: connection closed ]
I`m added to add auto_reconnect but I get the same error
var db = require("mongojs").connect(databaseUrl, collections, {auto_reconnect:true});
I get the following error when doing an update without passing a callback.
Error: Cannot use a writeConcern without a provided callback
at Collection.update (/home/node/node-service/releases/2013-04-26T19-18-35.711575192/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection.js:488:11)
at /home/node/node-service/releases/2013-04-26T19-18-35.711575192/node_modules/mongojs/index.js:156:65
at apply (/home/node/node-service/releases/2013-04-26T19-18-35.711575192/node_modules/mongojs/node_modules/thunky/index.js:16:28)
at null._get (/home/node/node-service/releases/2013-04-26T19-18-35.711575192/node_modules/mongojs/node_modules/thunky/index.js:27:3)
at Collection._apply (/home/node/node-service/releases/2013-04-26T19-18-35.711575192/node_modules/mongojs/index.js:154:7)
at Collection.(anonymous function) [as update] (/home/node/node-service/releases/2013-04-26T19-18-35.711575192/node_modules/mongojs/index.js:149:8)
at /home/node/node-service/releases/2013-04-26T19-18-35.711575192/server.js:1581:15
at Cursor.nextObject (/home/node/node-service/releases/2013-04-26T19-18-35.711575192/node_modules/mongojs/node_modules/mongodb/lib/mongodb/cursor.js:676:5)
at commandHandler (/home/node/node-service/releases/2013-04-26T19-18-35.711575192/node_modules/mongojs/node_modules/mongodb/lib/mongodb/cursor.js:658:14)
at null.<anonymous> (/home/node/node-service/releases/2013-04-26T19-18-35.711575192/node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js:1632:20)
I'm not familiar enough with the native mongodb driver to know if this is possible, but in drivers for other languages I'm not forced to create an array of all of the collections contained in my database.
Instead of this:
db = require('mongojs').connect('db', ['coll1', 'coll2', 'coll3', 'coll4', 'coll5', 'coll6', 'coll7', 'coll8', 'coll9']);
It would be much more convenient to be able to just do the following and have access to all of those collections:
db = require('mongojs').connect('db');
'npm install mongojs' installation attempt fails with message:
C:\nodejs\node_modules\mongojs\node_modules\mongodb\node_modules\kerberos\build\binding.sln : error MSB3411: Could not load the Visual
C++ component "VCBuild.exe". If the component is not installed, either 1) install the Microsoft Windows SDK for Windows Server 2008 a nd .NET Framework 3.5, or 2) install Microsoft Visual Studio 2008.
C:\nodejs\node_modules\mongojs\node_modules\mongodb\node_modules\bson\build\binding.sln : error MSB3411: Could not load the Visual C++
component "VCBuild.exe". If the component is not installed, either 1) install the Microsoft Windows SDK for Windows Server 2008 and . NET Framework 3.5, or 2) install Microsoft Visual Studio 2008.
Once Visual studio 2008 is installed, retry attempts results in following error message:
C:\nodejs\node_modules\mongojs\node_modules\mongodb\node_modules\kerberos\build
\kerberos.vcxproj(3,14): error MSB4066: The attribute "Label" in element is unrecognized.
C:\nodejs\node_modules\mongojs\node_modules\mongodb\node_modules\bson\build\bso
n.vcxproj(3,14): error MSB4066: The attribute "Label" in element is
unrecognized.
I'd hope that there would be some way to install mongojs without having Visual studio present.
Mongo db shell support "show collections" to list all the collections of a database.
How do I do this in javascript using mongojs?
The Mongo API allows _id fields to be types other than ObjectId provided it is unique (see: http://www.mongodb.org/display/DOCS/Object+IDs). For example, _id could be an ID provided by a third party that is unique but is not a 12 character string that ObjectId requires.
However, it seems like mongojs tries to automatically cast _id properties as ObjectIds, eliminating this functionality. Is there a way around this?
First big up to mongojs, it's by far the most intuitive driver/wrapper out there ;-)
Then, I'm trying to make an upsert:
db.Auth.update({
"user.id": socialId
},
new Auth(...),
{
upsert: true
}, function(err, doc) {
callback(err);
});
}
but need to know whether this update was an insert or an update. Is there a way to do that? How do we get access to getLastError() with mongojs?
Thanks a bunch!
I am fairly new to mongodb and just started using mongojs in my nodejs app.
I wish to find items using their _id.
I tried
db.abc.find({_id: req.params.id}, function(...) { ... })
&
db.abc.find({_id: "ObjectId("+req.params.id+")"}, function(...) { ... })
Either of them did not work. Can this be achieved?
I'm trying to use the group command as in the below example:
db.myCollection.group({
key: {},
cond: {t: {$gte: 86400}},
initial: {count: 0, online: 0},
reduce: function(doc, out) {
out.count++;
out.online += doc.online;
},
finalize: function(out) {
out.avgOnline = out.online / out.count;
}
}, function(err, curOnline) {
// ...
});
But I get the following error:
TypeError: boolean is not a function
at Collection.group.scope (/Users/James/Sites/goldfire/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection.js:1363:7)
at Db._executeQueryCommand (/Users/James/Sites/goldfire/node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js:1801:5)
at g (events.js:192:14)
at EventEmitter.emit (events.js:126:20)
at Db._callHandler (/Users/James/Sites/goldfire/node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js:1485:25)
at Server.connect.connectionPool.on.server._serverState (/Users/James/Sites/goldfire/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/server.js:478:30)
at MongoReply.parseBody (/Users/James/Sites/goldfire/node_modules/mongojs/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:127:5)
at Server.connect.connectionPool.on.server._serverState (/Users/James/Sites/goldfire/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/server.js:435:22)
at EventEmitter.emit (events.js:96:17)
at _connect (/Users/James/Sites/goldfire/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:148:13)
I see you also add custom findAndModify and remove methods but there's nothing in the docs about that.
Is there a reason why you don't accept safe as a parameter to findAndModify?
I get the following error when doing a find
:
[Error: limit requires an integer]
This only happens after 0.5.1. The odd thing is it appears to be calling the find twice, because if I log to the console the error, it gives me:
null
[Error: limit requires an integer]
In the code below, I set up a domain with an error listener that I would expect would catch the exception thrown within the find() callback:
var domain = require('domain');
var db = require('mongojs').connect('whatever', ['whatever']);
var dmn = domain.create();
dmn.on('error', function (err) {
console.log("Exception caught by domain:", err);
});
dmn.run(function() {
db.whatever.find({whatever: 'whatever'}, function (err, userinfo) {
throw (new Error());
});
});
What I'm seeing instead is node aborting with an exception thrown in domain.js:66.
Don't know enough about node to guess whether this is a node or a mongojs problem, but I did see a bug report in which somebody requested a similar fix to the fs module, so I guess it's module-specific?
I was experimenting locally and turned the mongod off to see what errors mongojs would give me when trying to do anything.
What I got was: [Error: failed to connect to [localhost:27017]]
I'm finding it difficult to log, pass around and overall kind of tricky to work with. Is there any common practice way to convert the returned errors to valid JS or cast them as a string at least?
I also don't know what all the possible errors are so I'm kind of worried about how to best implement this in a way that won't bite me in 2 months time.
Is mapReduce supposed to be supported by mongojs? I coulnd't find it in the code
If yes: please update README with an example
If not: it would be awesome if you could implement it
Keep up the good work, the syntax is great
I think it would be a nice feature to .bind() callback functions to the current collection, so that "this" refers to it. It would cut down on repeat code. Here's what it would look like:
db.mycollection.find(function(err, docs) {
// "this" refers to db.mycollection since it's a callback inside it
this.update({_id: 123}, {name: "MongoJS"}, function(err, updated) {
// wouldn't this be nifty?
});
});
If this is something that gets approved, I'd be glad to try to implement it. What do you guys think?
In this link, mongodb said it support upsert
by an operation.
I tried it in mongodb shell and it works fine.
But when I try the same update function in mongojs, it failed to insert the document if does not exist.
Here is the experiment:
In mongodb shell
> db.tc.find()
> db.tc.update({v:111},{'$push':{m:'a'}},true)
> db.tc.find()
{ "_id" : ObjectId("4fc58624f2e9e463dc04b1ad"), "m" : [ "a" ], "v" : 111 }
> db.tc.update({v:111},{'$push':{m:'b'}},true)
> db.tc.find()
{ "_id" : ObjectId("4fc58624f2e9e463dc04b1ad"), "m" : [ "a", "b" ], "v" : 111 }
>
Use mongojs in node.js interactive
> mongojs = require('mongojs')
{ ObjectId: [Function],
connect: [Function] }
> db = mongojs.connect('test')
....(lots of output)
> tc = db.collection('tc')
> callback = function(err, docs) {
... console.log(JSON.stringify(docs));
... }
[Function]
> tc.remove();
undefined
> tc.find({}, callback);
{ _oncursor: { get: [Function], put: [Function] } }
> []
> tc.update({v:111},{'$push':{m:'a'}}, true);
undefined
> tc.find({}, callback);
{ _oncursor: { get: [Function], put: [Function] } }
> []
>
the update(query, new_data, true)
does not work.
Is there any solution?
I'm trying to connect using
var mongo = require('mongojs');
mongo.connect('username:?&A*[email protected]:27017/my_database');
and mongojs 0.4.3 fails with this error:
aguilarlopez@prosito /tmp % node t.js
/private/tmp/node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js:210
if(databaseName.indexOf(invalidChars[i]) != -1) throw new Error("database
^
Error: database names cannot contain the character '.'
at validateDatabaseName (/private/tmp/node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js:210:59)
at new Db (/private/tmp/node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js:77:3)
at Object.<anonymous> (/private/tmp/node_modules/mongojs/index.js:200:17)
at /private/tmp/node_modules/mongojs/node_modules/common/index.js:135:6
at Object.step (/private/tmp/node_modules/mongojs/node_modules/common/index.js:155:2)
at Object.connect (/private/tmp/node_modules/mongojs/index.js:191:9)
at Object.<anonymous> (/private/tmp/t.js:3:7)
at Module._compile (module.js:446:26)
at Object..js (module.js:464:10)
at Module.load (module.js:353:31)
mongojs 0.4.0 works as expected.
var databaseUrl="mydb";
var collections = ["mycollection"];
var db = require("mongojs").connect(databaseUrl, collections);
... connects to mongod, then hangs until CTRL+C
With a find() query, the query executes correctly, but again node does not terminate.
I tried with node on Cygwin, then with the official Windows .MSI version.
[email protected]
[email protected]
node v0.6.11
Could please add support for connection to replica set?
for findAndModify with new: true, my latest install of mongojs is returning
[
{},
{
lastErrorObject: {},
value: {},
ok: 1}
]
instead of the previously expected value {}. Perhaps a change in the underlying operation of the native driver?
When calling update() on a collection, I received this stack trace:
TypeError: object is not a function
at Collection.update (/var/www//node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection.js:439:62)
at /var/www///node_modules/mongojs/index.js:167:6
at /var/www//node_modules/mongojs/node_modules/thunky/index.js:16:28
at [object Object]._get (/var/www//node_modules/mongojs/node_modules/thunky/index.js:27:3)
at [object Object]._apply (/var/www//node_modules/mongojs/index.js:161:7)
at [object Object].update (/var/www//node_modules/mongojs/index.js:156:8)
The query looked like this:
collection.update({
query : {_id : ObjectId()},
update : {$push : {pv : [ObjectId(), new Date()]}}
}, function(err, data) {});
Updating the query to the following fixed the error.
collection.update(
{query : {_id : ObjectId()}},
{update : {$push : {pv : [ObjectId(), new Date()]}}}
}, function(err, data) {});
See here.
I really love this project so far, but I'm trying to use the node module connect-mongodb for session management, and it requires you to pass in a mongodb object when you create an instance of the session store. I can see in your source that you are creating a mongodb instance in exports.connect (with the line, "new mongo.Db(...)"), but it doesn't appear that this value is available externally.
Would it be possible to expose this object so that we could access the mongodb instance directly? Is it already possible, and I'm just not seeing how? Thanks!
I love the idea of this project, and would like to use it in order to mock mongodb in my tests.
Right now I'm using 'mongoskin' library (provides promises on top of mongo-native) and it doesn't work with it :(
I'm using remap ( https://github.com/dominictarr/remap ) to load 'mongojs' rather than 'mongodb' under mongoskin, but mongoskin crashes while init beacause it wants to wrap require('mongodb').Admin and mongojs does not provide it.
When i want to use chained db name like: db.kbz01.members
i get an error :
var members = db.kbz01.members;
^
TypeError: Cannot read property 'members' of undefined
There's no problem using those collection names in the mongo shell.
Hi there,
If I have db.myCollection.find(searchTerm, callback), is there any way to pass a variable to the callback?
Thanks
James
Hi,
I'm getting this error on a fresh mongodb install.
TypeError: Cannot read property '_serverState' of undefined
Seem like the latest mongodb also had the same problem with on mongo-skin
ElectricDynamite/pasty-server#11
I just made a simple server which receives data from client via http protocols and store them into the mongodb. But the server always crashes with this error:
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: accept EMFILE
at errnoException (net.js:769:11)
at TCP.onconnection (net.js:1017:24)
source code is like this:
app.get('/log', function(req, res) {
var db = require("mongojs").connect("mydb");
var collection = db.collection(req.query.id);
collection.save(req.query, function(err, saved) {
var result = (err || !saved) ? err + " : log not saved " : req.query;
console.log(result);
res.send(result);
});
});
The server finds a collection by an id argument which is received by a client - most of the time, the id is identical - and it stores the whole data which is represented by json format.
A significant thing is, in this case, whenever the requests are received, the count of the file's descriptor that are used by this process always gets bigger. I verified it using this shell command:
ls -l /proc/<process id>/fd|wc -l
If I remove the lines that are dealt with mongojs, nothing happens.
I know that a file descriptor is always used by a process when it opens a file or connects somewhere. But I guess this should not happen because this is not the case for the concurrent condition.
If this is a bug, could you please recommend a work around for this issue?
My code looks like:
console.log({_id: id});
db.users.findOne({_id: id}, callback);
but the result in null, even tho a record for that id exists and id itself is a valid hex string with a correct value.
Then I try:
db.users.findOne(id, callback);
for which it throws up [TypeError: Object.keys called on non-object]
Am I doing something wrong? Or is a bug?
Terribly sorry to be raising this as an issue and not fixing it itself. I'll be terribly busy over the next couple of days but I can have a look at this Thursday onward. Meanwhile perhaps its good to report it as an issue.
The distinct() function allows me to create a list from a collection like so :
//Collection
{
'country': 'Japan',
'currency': 'yen'
}
...
db.currency.distinct({'country'}) // Gives me ['Japan', 'Canada', 'Trinidad & Tobago'].
Any plans on supporting it?
When I call myCursorVar.count() on a cursor with approx. 17,000 documents, it returns undefined, every time. I also tried doing myDb.myCollection.count(), just for kicks, and also got undefined. Using version 0.4.5.
I experienced this error several times when using the db.ObjectId() function,
I finally managed to resolve it by changing the index.js in mongojs module from
that.ObjectId = function(id) {
return new mongodb.BSONNative.ObjectID(id);
};
to
that.ObjectId = function(id) {
return new mongodb.BSONPure.ObjectID(id);
};
I wanted to use the test for existing collection during createCollection, no error shown if it exists though.
Something like this from here
http://mongodb.github.com/node-mongodb-native/api-articles/nodekoarticle1.html
db.collection('test', {w:1}, function(err, collection) {});
db.createCollection('test', {w:1}, function(err, collection) {});
The .remove() command in mongojs does not seem to obey the Mongo spec in removing only one document. The following is from the Mongo documentation:
The following operation deletes a single document from the bios collection where the turing field equals true:
db.bios.remove( { turing: true }, 1 )
but this doesn't seem to be properly implemented in mongojs -- instead, all documents that match the query are deleted.
(I also can't find any documentation for what the callback function in .remove() returns for "value." I'm interpreting it as the number of documents that matched the condition and were deleted.)
Where?
Is there a reason why if I have a specific "result" object from a query and I want a make an update, the save function fails,
db.users.save(result,function(err, saved) {
if( err || !saved ) console.log("update failed - err="+err);
else console.log("User "+saved.id+" updated");
});
yet the equivalent .update() function works fine?
db.users.update( { _id: result._id }, result, /upsert/ true, function(err, saved){
if( err || !saved ) console.log("update failed - err="+err);
else console.log("User "+saved.id+" updated");
});
Both are completely equivalent and legal, see http://www.mongodb.org/display/DOCS/Updating.
I would give a suggested fix but I don't yet have the debugger up and running with node to see where things hang.
Might be worthwhile pointing out in the Readme not to use the .save() function unless creating new collection entries.
Maybe I'm just missing something, but I typically converted a string
into an ObjectId
with the following code:
var objectID = require("mongojs").ObjectId("objectidhere");
This is no longer defined. Was this moved? Is there a better way to do this that I'm missing? I'm assuming this probably isn't a bug, but I wanted to post it here to ideally get help, or alert you to the fact that this no longer works (if it should).
Tested in v0.4.5.
Running a query with a $where is ignored, and is treated as .find(), by returning all items in a collection.
I was wondering if Mongojs does support the continueOnError or keepGoing options that come with native-mongo?
If yes, how? an example would be appreciated.
Thanks in advance.
What I usually do is:
As I added a piece of code into Mongojs index.js:
function(db, next) {
this.db = db;
db.on("close", function(error){
console.log("Connection to the database was closed!");
next(error, false)
});
if (options.username) {
db.authenticate(options.username, options.password, next);
} else {
next(null, true);
}
}
Although it printed this log, I just want to know that is what I do below uncommon in the production env? there is no need to worry about it?
Anyway I just want to reconnect if lost.
Thanks in advance.
The line var db = require('mongojs').connect('username:[email protected]/node', ['files']);
works fine for me, but when I do var db = require('mongojs').connect('node', ['files']);
I get,
Error: db object already connecting, open cannot be called multiple times at Db.open (/var/locker/kyros/Node/Flashbank/Node/node_modules/mongojs/node_ modules/mongodb/lib/mongodb/db.js:236:11)
Hi,
My connection string is:
root:[email protected]:40769/maker_ad_planner
I do:
mongojs = require 'mongojs');
db = mongojs(connection_string);
db.collection('stuff').find({}, function(err, results) {
return log.info(err, results);
});
And I get:
2013-04-12 23:41:02.512] (info) { [MongoError: auth fails] name: 'MongoError', errmsg: 'auth fails', ok: 0 } undefined
What am I doing wrong?
If used with MongoHQ connections easily gets lost, and mongojs doesn't seem to reconnect. This leads to the following error.
Error: notConnected
at [object Object].executeCommand (.../node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js:693:41)
at Collection.count (.../node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection.js:492:11)
at .../node_modules/mongojs/index.js:186:13
at /home/gett/workspace/gett-frontend/node_modules/common/index.js:103:3
at Object.get (.../node_modules/common/index.js:218:4)
at [object Object]._exec (.../node_modules/mongojs/index.js:185:21)
at [object Object].count (.../node_modules/mongojs/index.js:146:7)
at Object.<anonymous> (.../user-server/index.js:283:14)
at .../node_modules/common/index.js:135:6
at Object.step (.../node_modules/common/index.js:155:2)
It should probably reconnect lazily.
Trying to use $group in the Aggregation Framework.
options = opts.readPreference || opts.explain ? args.pop() : {}
^
TypeError: Cannot read property 'readPreference' of undefined
Hi,
I love using mongojs. Thanks to its clean syntax.
Recently, I had come across an interesting npm package named 'trycatch' ( https://github.com/CrabDude/trycatch ) that implements try..catch for asynchronous code. It catches an exception that is thrown by an async code, as if it had happened in a sync code. While it works with async file readings., etc, I am unable to succeed with mongojs. Out of curiosity, I went ahead to try with mongo-native code and see that it works well. I am able to throw an exception in any of the deep-down async callback and catch it.
Could you guys help me out to figure out a way to use it with mongojs ?
working: async file reading
var trycatch = require('trycatch');
trycatch(function init() {
fs.readFile(__filename, function (err, data) {
console.log(''+data);
throw new Error("yahoooo. will be caught");
});
},
function onerror(err) {
console.log("This is a scoped error handler!\n", err.stack);
}
);
not working: mongojs async find()
trycatch(function init() {
var mongojs = require('mongojs');
db = mongojs.connect('localhost:27017/mydb', ['users']);
db.users.find(function (err, doc) {
console.log(doc);
throw new Error("yahoooo. You can't catch me");
});
},
function onerror(err) {
console.log("This is a scoped error handler!\n", err.stack);
}
);
working : mongo-native find()
trycatch(function init() {
testmongo();
},
function onerror(err) {
console.log("This is a scoped error handler!\n", err.stack);
}
);
function testmongo() {
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var host = 'localhost';
var port = 27017;
console.log("Connecting to " + host + ":" + port);
var db = new Db('mydb', new Server(host, port, {}));
db.open(function(err, db) {
db.collection('users', function(err, collection) {
collection.find(function(err, cursor) {
cursor.each(function(err, item) {
console.dir(item);
throw new Error("yahoooo. will be caught");
});
});
});
});
}
I have node + extreme + mongojs server. On startup I invoke db = mongo.connect(...)
. Everything is working fine when one first runs mongod and then the server.
If, however, I forget running mongod first and run it after the server, any query fails with "failed to connect to". The only workaround is to create the db object again (or restart the server).
Now, I have noticed that mongojs sets the auto_reconnect
server option to the native driver. So, running mongod after the server should work, but it does not.
The issue is also discussed here - http://stackoverflow.com/questions/12216930/how-to-rerun-the-request-handler-in-node-express/12217525#comment16369674_12217525
I'm trying to use mongojs in conjunction with connect-mongo. This was working fine several months ago, but I recently decided to blanket upgrade everything and am now running into problems.
var express = require('express')
, mongojs = require('mongojs')
, MongoStore = require('connect-mongo')(express);
var collections = ["users"];
var db = mongojs("db", collections);
var sessionStore = new MongoStore({ db: db });
The above complains about calling open twice.
/home/ec2-user/server/node_modules/mongodb/lib/mongodb/connection/server.js:562
throw err;
^
Error: db object already connecting, open cannot be called multiple times
at Db.open (/home/ec2-user/server/node_modules/mongodb/lib/mongodb/db.js:224:11)
at /home/ec2-user/server/node_modules/mongojs/index.js:235:8
at apply (/home/ec2-user/server/node_modules/mongojs/node_modules/thunky/index.js:16:28)
at /home/ec2-user/server/node_modules/mongojs/node_modules/thunky/index.js:20:25
at /home/ec2-user/server/node_modules/mongojs/index.js:206:4
at /home/ec2-user/server/node_modules/mongodb/lib/mongodb/mongo_client.js:334:7
at /home/ec2-user/server/node_modules/mongodb/lib/mongodb/db.js:258:14
at null. (/home/ec2-user/server/node_modules/mongodb/lib/mongodb/connection/server.js:374:9)
at g (events.js:183:14)
at EventEmitter.emit (events.js:108:17)
Switching to var sessionStore = new MongoStore({ db: "db" });
instead avoids the issue, but means having multiple connections open (which I'd like to avoid).
connect-mongo checks db.openCalled
before calling open (which is undefined
on the mongojs object). I used to pass db.client
to MongoStore's constructor, but that appears to have been removed.
Manually setting db.openCalled = true;
avoids the exception, but introduces issues later on (as the variable is getting set on the wrapper and not the db itself).
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.