Giter Club home page Giter Club logo

mongojs's People

Contributors

bendytree avatar christophwalcher avatar forbeslindesay avatar freeall avatar ianjorgensen avatar janowsiany avatar jonnyburger avatar kapetan avatar lionvs avatar longbill avatar lordkhonsu avatar lpinca avatar lukechilds avatar mafintosh avatar mcollina avatar mortenanders avatar naartjie avatar naugtur avatar necromos avatar nmn avatar olegam avatar orta avatar osterjour avatar saintedlama avatar shakefu avatar sorribas avatar sri-rang avatar watson avatar xantorres avatar xissy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongojs's Issues

Error using tailable cursor

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.

Driver caches insert requests in memory and can produce out of memory failure

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

[Error: connection closed ]

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});

Cannot use a writeConcern without a provided callback

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)

Make [collections] optional on connect

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');

MongoJS installation fails on windows 8 / 64b

'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.

Don't force _id to be ObjectId

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?

Accessing getLastError()

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!

Find by _id

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?

Group command not working

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)

Documentation for findAndModify and remove

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?

Error: limit requires an integer

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]

Exceptions thrown within callbacks aren't caught by domain

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?

Working with returned error types proving difficult

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.

mapReduce support?

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

Using "this" keyword to access the current collection

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?

Mongojs don't support upsert?

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?

0.4.{1-3} is unable to parse the connection url of the form username:password@host:port/database

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.

Node does not terminate

 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

"TypeError: object is not a function" when updating using single query object, vs separate query and update params.

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) {});

Allow access to the mongodb instance created

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!

Exposing mongodb-native API

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.

Monogjs with chained db names.

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.

Error: accept EMFILE

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?

.findOne by id .. broken?

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.

Support for distinct?

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?

db.ObjectId does not work

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);
};

Remove only one document?

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.)

.save() doesn't work

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.

What happened to ObjectId?

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).

continueOnError / keepGoing Option

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.

Err connection closed after my laptop wakeups

What I usually do is:

  1. Run node sever, so the server is running
  2. Sleep my laptop every night
  3. Next day wakeup it, in terminal the server is still running
  4. Execute any db operation, get error "Error connection closed" emitted by '\mongodb\connection\server.js:564:45

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.

Can't connect with just database

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)

auth fails

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?

Doesn't reconnect if connection is lost

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.

readPreference error

Trying to use $group in the Aggregation Framework.

  1. can Aggregation Framework be used with mongojs?
  2. This is the error:

options = opts.readPreference || opts.explain ? args.pop() : {}
^
TypeError: Cannot read property 'readPreference' of undefined

using mongojs with asynchronous trycatch module

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");
                });
            });
        });
    });
}

The `auto_reconnect` server option does not work.

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

open called multiple times with connect-mongo

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).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.