GithubHelp home page GithubHelp logo

marcello3d / node-mongolian Goto Github PK

View Code? Open in Web Editor NEW
349.0 18.0 51.0 487 KB

[project inactive] Mongolian DeadBeef is an awesome Mongo DB driver for node.js

Home Page: https://groups.google.com/group/node-mongolian

License: zlib License

JavaScript 100.00%

node-mongolian's Introduction

Project Inactive

I am no longer have the time to work on this project. Feel free to fork!

Mongolian DeadBeef

Mongolian DeadBeef is an awesome Mongo DB node.js driver that attempts to closely approximate the mongodb shell.

Build Status

Introduction

Mongolian DeadBeef and its documentation is super under construction! Go check out examples/mongolian_trainer.js and the rest of the source!

Unlike other MongoDB node.js drivers, Mongolian DeadBeef is built from the ground up for node.js, using node-buffalo for BSON/message serialization.

v0.1.15 Upgrade notes

0.1.15 uses node-buffalo instead of mongodb-native for serialization, this means a few incompatibilities:

  • The helper methods on ObjectId are removed, use the ObjectId constructor to parse hex strings
  • Code type is removed, use vanilla function instances instead
  • DBRef is not supported
  • Error messages may be different

Installation

DISCLAIMER: The API is experimental (but stabilizing). I will be adding, removing, and changing the API in the interest of a solid API. Use at your own risk

You can either clone the source and install with npm link, or install the latest published version from npm with npm install mongolian.

Running Tests

Run the tests with npm test.

Motivation

Not a fan of existing asynchronous mongodb apis for node.js, I set out to write my own. To avoid completely reinventing the wheel, much of the Mongolian DeadBeef API is inspired by the mongodb shell.

High level principles:

  • Less is more
    • Nothing is added without careful consideration
    • Remove everything but the essentials
    • Each refactor should remove as much unnecessary lines of code as possible
  • Fail early and often
    • If I can easily detect a programmer error, an exception will be thrown

Notes:

  • mongodb is pretty simple, much of its functionality is defined as queries on special databases
    • This allows for lots of code reuse
  • Avoid callbacks unless they are absolutely necessary

Basics

Most of the work in MongolianDeadBeef doesn't occur until a query is actually made. This means that simple operations are fast and synchronous. Currently there is one connection per server.

Examples

var Mongolian = require("mongolian")

// Create a server instance with default host and port
var server = new Mongolian

// Get database
var db = server.db("awesome_blog")

// Get some collections
var posts = db.collection("posts")
var comments = db.collection("comments")

// Insert some data
posts.insert({
    pageId: "hallo",
    title: "Hallo",
    created: new Date,
    body: "Welcome to my new blog!"
})

// Get a single document
posts.findOne({ pageId: "hallo" }, function(err, post) {
    ...
})

// Document cursors
posts.find().limit(5).sort({ created: 1 }).toArray(function (err, array) {
    // do something with the array
})
posts.find({ title: /^hal/ }).forEach(function (post) {
    // do something with a single post
}, function(err) {
    // handle errors/completion
})

Connections and Authentication

// Create a server with a specific host/port
var server = new Mongolian("mongo.example.com:12345")


// Authenticate a database
db.auth(username, password)


// Supported connection url format: [mongo://][username:password@]hostname[:port][/databasename]
// Use uri-encoding for special characters in the username/password/database name

// Database/auth shorthand (equivalent to calling db() and auth() on the resulting server)
var db = new Mongolian("mongo://username:[email protected]:12345/database")

// Connecting to replicasets:
var server = new Monglian(
    "server1.local",
    "server2.local",
    "server3.local:27018"
)

Logging

By default, Mongolian logs to console.log, but you can override this by specifying your own log object (any object that provides debug, info, warn, and error methods):

var server = new Mongolian({
    log: {
        debug: function(message) { ... },
        info: function(message) { ... },
        warn: function(message) { ... },
        error: function(message) { ... }
    }
})

var server = new Mongolian('server1.local', 'server2.local', {
    log: { ... }
})

BSON Data Types

Mongolian DeadBeef uses node-buffalo's BSON serialization code. Most BSON types map directly to JavaScript types, here are the ones that don't:

var Long =      require('mongolian').Long       // goog.math.Long - http://closure-library.googlecode.com/svn/docs/class_goog_math_Long.html
var ObjectId =  require('mongolian').ObjectId   // new ObjectId(byteBuffer or hexString)
var Timestamp = require('mongolian').Timestamp  // == Long
var DBRef =     require('mongolian').DBRef      // not supported yet

GridFS

The Mongo shell doesn't support gridfs, so Mongolian DeadBeef provides a custom Stream-based GridFS implementation. It consists of two main classes, MongolianGridFS and MongolianGridFile. You can get a MongolianGridFS object from a database with the gridfs([gridfs name]) function.

// Get a GridFS from a database
var gridfs = db.gridfs() // name defaults to 'fs'

// Writing to GridFS consists of creating a GridFS file:
var file = gridfs.create({
    filename:"License",
    contentType:"text/plain"
})
// And getting writable Stream (see http://nodejs.org/docs/v0.4/api/streams.html#writable_Stream )
var stream = file.writeStream()

// You can then pipe a local file to that stream easily with:
fs.createReadStream('LICENSE').pipe(stream)

// Reading a file from GridFS is similar:
gridfs.findOne("License", function (err, file) {
    if (!err && file) {
        // Get the read stream:
        var stream = file.readStream()

        // You could then pipe the file out to a http response, for example:
        stream.pipe(httpResponse)
    }
})

// You can access metadata fields from the file object:
file.length // might be a Long
file.chunkSize
file.md5
file.filename
file.contentType // mime-type
file.uploadDate
// These two are optional and may not be defined:
file.metadata
file.aliases

// If you make any changes, save them:
file.save()

Mongodb Shell Command Support

Nearly all commands are identical in syntax to the mongodb shell. However, asynchronous commands that go to the server will have an optional node.js style callback parameter.

Currently most commands starting with get are named without the get. Some of the getters are implemented as values instead of functions.

  • Bold functions are supported
  • Italicized functions are supported with different syntax
  • Everything else is currently unsupported

There will likely be methods below that are never supported by Mongolian DeadBeef, since I'm targetting a slightly different use case.

Databases

From http://api.mongodb.org/js/1.8.1/symbols/src/shell_db.js.html

  • db.addUser(username, password[, readOnly=false][, callback])
  • db.auth(username, password)
  • db.cloneDatabase(fromhost)
  • db.commandHelp(name) returns the help for the command
  • db.copyDatabase(fromdb, todb, fromhost)
  • db.createCollection(name, { size : ..., capped : ..., max : ... } )
  • db.currentOp() displays the current operation in the db
  • db.dropDatabase() - see callback note below
  • db.eval(func[, arg1, arg2, ...][, callback]) run code server-side - see callback note below
  • db.getCollection(cname) implemented as db.collection(cname)
  • db.getCollectionNames() implemented as db.collectionNames(callback)
  • db.getLastError() - just returns the err msg string
  • db.getLastErrorObj() implemented as db.lastError(callback) - return full status object
  • db.getMongo() get the server connection object implemented as db.server
  • db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair
  • db.getName() implemented as db.name
  • db.getPrevError() (deprecated?)
  • db.getProfilingStatus() - returns if profiling is on and slow threshold
  • db.getReplicationInfo()
  • db.getSiblingDB(name) get the db at the same server as this one
  • db.isMaster() check replica primary status
  • db.killOp(opid) kills the current operation in the db
  • db.listCommands() lists all the db commands
  • db.printCollectionStats()
  • db.printReplicationInfo()
  • db.printSlaveReplicationInfo()
  • db.printShardingStatus()
  • db.removeUser(username[, callback]) - see callback note below
  • db.repairDatabase()
  • db.resetError()
  • db.runCommand(cmdObj[, callback]) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }
  • db.serverStatus()
  • db.setProfilingLevel(level,) 0=off 1=slow 2=all
  • db.shutdownServer()
  • db.stats()
  • db.version() current version of the server

Collections

From http://api.mongodb.org/js/1.8.1/symbols/src/shell_collection.js.html

  • collection.find().help() - show DBCursor help
  • collection.count(callback)
  • collection.dataSize()
  • collection.distinct(key[, query], callback) - eg. collection.distinct( 'x' )
  • collection.drop([callback]) drop the collection - see callback note below
  • collection.dropIndex(name[, callback]) - see callback note below
  • collection.dropIndexes()
  • collection.ensureIndex(keypattern[,options][, callback]) - options is an object with these possible fields: name, unique, dropDups - see callback note below
  • collection.reIndex()
  • collection.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return. e.g. collection.find( {x:77} , {name:1, x:1} ) - returns a cursor object
  • collection.find(...).count()
  • collection.find(...).limit(n)
  • collection.find(...).skip(n)
  • collection.find(...).sort(...)
  • collection.findOne([query][callback])
  • collection.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } ) ex: finds document with comment value 0, increase its 'count' field by 1, and return the updated document. collection.findAndModify( {query: {comment:'0'}, update : {"$inc":{"count":1}}, 'new': true}, function (err, doc) { console.log(doc) })
  • collection.getDB() get DB object associated with collection implemented as collection.db
  • collection.getIndexes() implemented as collection.indexes(callback)
  • collection.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
  • collection.mapReduce( mapFunction , reduceFunction , [optional params][, callback])
  • collection.remove(query[, callback]) - see callback note below
  • collection.renameCollection( newName , [dropTarget] ) renames the collection.
  • collection.runCommand( name , [options][, callback]) runs a db command with the given name where the first param is the collection name
  • collection.save(obj[, callback]) - see callback note below
  • collection.stats()
  • collection.storageSize() - includes free space allocated to this collection
  • collection.totalIndexSize() - size in bytes of all the indexes
  • collection.totalSize() - storage allocated for all data and indexes
  • collection.update(query, object[, upsert_bool, multi_bool][, callback]) - see callback note below
  • collection.validate() - SLOW
  • collection.getShardVersion() - only for use with sharding

Cursors

From http://api.mongodb.org/js/1.8.1/symbols/src/shell_query.js.html

  • cursor.sort( {...} )
  • cursor.limit( n )
  • cursor.skip( n )
  • cursor.count() - total # of objects matching query, ignores skip,limit
  • cursor.size() - total # of objects cursor would return, honors skip,limit
  • cursor.explain([verbose])
  • cursor.hint(...)
  • cursor.showDiskLoc() - adds a $diskLoc field to each returned object
  • cursor.toArray(callback) - unique to Mongolian DeadBeef
  • cursor.forEach(func, callback) - calls func for each document, and callback upon completion or error
  • cursor.print() - output to console in full pretty format
  • cursor.map( func ) - map documents before they're returned in next, toArray, forEach
  • cursor.hasNext()
  • cursor.next([callback]) - returns the next document or null if there are no more

Callbacks

Callbacks take the standard node.js format: function(error, value)

Mongodb handles write operations (insert, update, save, drop, etc.) asynchronously. If you pass a callback into one of these methods, this is equivalent to immediately calling db.lastError(callback) on the same server/connection. Passing a null value will not send a getLastError command to the server.

Currently there is no way to specify the write concern on these inlined callbacks.

Todo

  • Connection pooling
  • Various utility methods
  • More unit tests
  • Documentation
  • Cleanup

Contributing

Try it out and send me feedback! That's the best help I could use right now. Unit tests are good, too.

License

Mongolian DeadBeef is open source software under the zlib license.

node-mongolian's People

Contributors

filirom1 avatar jazzzz avatar jondum avatar jteneycke avatar marcello3d avatar sevifives avatar taler-zz avatar xcoderzach avatar yorkie avatar yosefd 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

node-mongolian's Issues

does not re-connect

When mongodb gets restarted the node app loses the connection is no longer working. Mongolian should just re-connect in such an event.

Shared Connection problem..?

Is it a good way to share mongodb connection between users?
Let's say 100 incoming requests come to node, those 100 requests share the same db connection or should we separate them to 100 db connections?
And if we choose to separate connections, what if 2,000 incoming requests come to node? can mongodb handle 2,000 db connections in case we didn't do sharding.

How to connect mongo sharding?

Here's my log

mongo://192.168.254.191:30001: Connected
mongo://192.168.254.191:30001: Connected
Finished scanning... primary? no

uncaughtException : Error: Could not connect to primary: Error: Server Error: { '$err': 'assertion s/config.h:108', code: 0 }

at EventEmitter. (/home/user/Documents/www/myApplication/node_modules/mongolian/lib/server.js:117:49)
at EventEmitter.g (events.js:143:14)
at EventEmitter.emit (events.js:81:20)
at /home/user/Documents/www/myApplication/node_modules/mongolian/lib/server.js:75:34
at /home/user/Documents/www/myApplication/node_modules/mongolian/lib/db.js:62:13
at /home/user/Documents/www/myApplication/node_modules/mongolian/lib/util.js:19:18
at [object Object].next (/home/user/Documents/www/myApplication/node_modules/mongolian/lib/cursor.js:159:9)
at /home/user/Documents/www/myApplication/node_modules/mongolian/lib/cursor.js:163:18
at /home/user/Documents/www/myApplication/node_modules/mongolian/lib/util.js:19:18
at /home/user/Documents/www/myApplication/node_modules/mongolian/lib/cursor.js:117:9
Finished scanning... primary? no

ensureIndex throws error about key name

I issue collection.ensureIndex({"foo.bar": 1}, {background: 1}, function() {});

and mongolian throws an error "Error: key foo.bar must not contain '.'

This is a bug... Key names very much so can contain a dot... its the only way I know to do embedded doc keys!

going to have to go back to mongoskin until this is fixed :(

forEach is nesting?

var mm = require(MVC_MODELS);

module.exports.run = function() {
mm.model('mapimage_tile', function(err, mit_model) {
var tile_list = [];
var cursor = mit_model.find({}, {heights: 0});

    function _process_tile(tile){
       console.log('tile', tile._id, 'r', tile.tile_i, 'c', tile.tile_j);
    }

    function _done(){
        console.log('------- done ------');
    }
    cursor.forEach(_process_tile, _done);
});

}

for a very large collection returns the error:

console.js:40
var str = String(f).replace(formatRegExp, function(x) {
^
RangeError: Maximum call stack size exceeded

Seems to me the call stack should be fairly flat shouldn't it? This might not be a mongolian error, but I thought I'd bring it to your attention anyway.

ThreadSafe array

I peeked at the code to see how you collect all the records before you return the array.

Is that thread safe, if called my many 'threads'?

Closure would be traditional.

(or fibers, actors, chain of responsibility).

What do you think?

automatic collection initializing [enhancement]

Hey, great lib! Been searching for exaclty this... looked through tons of mongo node libs. It just makes sense mimicking the shell, why learn 2 different syntaxes?

Anyhow, had a suggestion, couldn't this code:

var db = server.db("awesome_blog")

var posts = db.collection("posts")

var comments = db.collection("comments")

Be replaced with just:
var db = server.db("awesome_blog")

... and the collections are automatically detected / initialized, basically that the following would happen behind the scenes:

db.posts = db.collection("posts")

db.comments = db.collection("comments")

... then we access the finders etc with db.posts.find() .. just as in the shell. Wouldn't this mimick the shell even more?

Limits not working

The following code will call forEach for as many "things" as there are in the database, not 5

it recursively calls saveThing 10 times and then runs a query with limit 5 and forEaches the result, toArray also does not respect the limit property.

var Mongolian = require("mongolian")
  , server = new Mongolian()
  , db = server.db("awesome")
  , collection = db.collection("things") 
  , i = 0
  , saveThing 

saveThing = function(done) {
  if(i < 10) {
    collection.insert({title:"w00t" + i, awesome:true}, function() { saveThing(done) })
    i++
  } else {
    done()
  }
}

saveThing(function() {
  var cursor = collection.find({awesome:true}).limit(5)
  i = 0
  cursor.forEach(function(err, item) {
    console.log(i++)
  }) 
}) 

Upsert not returning object in callback

I am having a problem when executing an upsert, that the object doesn't get returned in the callback. Also, the error object is null in the callback, so that is pretty weird. So the error object is null, and the object passed as a second parameter is undefined. When I check the database directly, the object is indeed there. Have you seen this before?

query the database from the client?

I'm trying to query the database from the client sorta like this:

     var query = {
       "selector":{
         "type": "comment"
       },
       "options":{
         "sort": {
           "t":-1
         }
       }
     }
     db(query, function (data) {
       renderComments (data);
     });

Is there a recommended way of passing this kind of query from the client?

I'm thinking about using RPC or something.

crash in cursor.js

I'm trying out the simplest code possible and it's resulting in a crash. My testscript is here http://pastie.org/1745380 ... + the my node-version and the output when the script crashes.

The database/collection does indeed exist, from mongo console:

db.screens.find().length()
1

server.close() is not closing everything (node doesn't exit)

Hi there,

I use mongolian inside a web app. Basically, when I connect to MongoDB I do not provide any parameters, the defaults seems to work fine for me :-).

Anyway: When a connection is not longer needed, is does not get closed. It is closed when I stop Node.js manually using Ctrl+C, but up to that point the connections stay open.

Playing around with the keepAlive parameter did not have any effect, and calling close() manually did not have any effect either.

What am I doing wrong?

Or is closing connections something you can let mongolian care about? Isn't there a problem if 100's or 1000's of connections are open at the same time?

Cheerio,

Golo

findandmodify example?

I want to find a document, update it, and return it. Your documentation is a tad unclear.

Trying this:

collection.findAndModify( {query: {comment:'0'}, update : {"$inc":{"count":1}}, 'new': true}, function (doc) {
  console.log(doc)
})

"Error: callback is not a function!" when trying to call findOne(...)

When I try to do a simple query on a collection, such as:

var Mongolian = require("mongolian")
var server = new Mongolian
var db = server.db("test")
var docs = db.collection("docs")
docs.findOne({}, function(err, doc) { console.log(doc) })

I get the error:

Error: callback is not a function!
    at [object Object].next (/home/jamalex/node/node_modules/mongolian/lib/cursor.js:153:48)
    at [object Object].findOne (/home/jamalex/node/node_modules/mongolian/lib/collection.js:53:42)
    at [object Context]:1:6
    at Interface.<anonymous> (repl.js:171:22)
    at Interface.emit (events.js:64:17)
    at Interface._onLine (readline.js:153:10)
    at Interface._line (readline.js:408:8)
    at Interface._ttyWrite (readline.js:585:14)
    at ReadStream.<anonymous> (readline.js:73:12)
    at ReadStream.emit (events.js:81:20)

It does the same thing no matter where I put the callback function (1st, 2nd, or 3rd argument). I also get the same error when I try to run the findOne code from the main example. The find() code seems to work, though I too get a stack overflow (as others reported) when doing a forEach on a large cursor.

I'm using node v0.4.11, and mongolian 0.1.10 (the one npm just installed), on 64bit Ubuntu 11.04. Thanks!

collection.find() expected results, api change

In the mongo shell, db.collection.find() returns all documents, however, in mongolian, the same command will return a cursor. What's with the discrepancy? Shouldn't just running db.collection.find(query, callback) give you all documents in that collection that match the query?

node 0.4.4 crashes with latest mongolian

Seems like mongolian is trying to use a console.debug() which isn't defined in latest vanilla node.

console
{ log: [Function],
info: [Function],
warn: [Function],
error: [Function],
dir: [Function],
time: [Function],
timeEnd: [Function],
trace: [Function],
assert: [Function] }

Save callback gets no data

When I call the script below, the save callback is not fed anything.

var Mongolian = require('mongolian');
module.exports.run = function() {

    var server = new Mongolian();
    var db = server.db('ac');
    var foo = db.collection('foo');

   // console.log('f == ', foo);
    var d = {
        a: 1,
        b: 6
    };

    foo.insert(d);

    foo.findOne({
        b: 6
    }, function(err, f) {
        console.log('found ', f);

        f.c = 3;

        foo.save(f,  function(err, f2) {
            console.log('saved: ', err, f2);

            foo.findOne({
                b: 6
            }, function(err, f) {
                console.log('found again ', f);
            })
        });
    })

}

/** result
loading test /Users/dave/Documents/Arena_Colles/test/ins_upd.js
mongo://localhost:27017: Connected
mongo://localhost:27017: Initialized as primary
mongo://localhost:27017: Connected to primary
Finished scanning... primary? mongo://localhost:27017
found { a: 1, b: 6, _id: 4e15cfc9fa62237e01000001 }
saved: null undefined
found again { a: 1, b: 6, _id: 4e15cfc9fa62237e01000001, c: 3 }
*/

Connection closed ?

When using mongodb native or mongoose the connection's always open when the server is started.

so I can do:

  db.collection('comment', function (err, collection) {
    server.db.comment = collection
  });

and then I have server.db.comment always available to add to.

But in Mongolian the connection seems to close immediately? Is this intended behavior? Am I misunderstanding the message?

Thanks.

RFC - use mongo shell source js files directly

Before finding this repo I started playing around with the idea of including only lightly modified files from https://github.com/mongodb/mongo/tree/master/shell

by lightly modified I mean for example appending this to the end of collection.js

module.exports.DBCollection = DBCollection;
module.exports.MapReduceResult = MapReduceResult;

and have something like this as the module index.js : https://gist.github.com/30ddac8c67a940c641ab

My current code is only a proof of concept (though you can load it, and get some semi-valid responses, it doesn't connect and therefore isn't useable - yet) but if I can get it to work at all I'll publish it and point at it :). My intention would be to have a node interface which is always up to date with the mongo-shell syntax and functionality.

As a project with a similar goal I wonder if you had also considered doing this, or if you have an opinion as to the viability of the general idea.

Memory Spike help?

I am writing a series of updates that updates a collection with a large number of integers:

//image rows: 5632 image.cols: 11520

       for (var i = 0; i < i_limit; i += scale)
            for (var j = 0; j < j_limit; j += scale) {
                var heights = _chunk(image_data, i, i + scale, j, j + scale); // returns a 128 x 128 nested array of ints
                var query = {min_image_i: i, min_image_j: j, image: image._id};
                var set_heights = {"$set": {heights: heights}};
                mit_model.update(query, gcb, set_heights); // note - my custom model switches the order

// of the parameters a bit.
}

I get around a thousand loops before it crashes.

Is there any way I can flush something to improve performance?

You want to update to 0.9.4-4 of the mongodb

Hi Marcello

you want to use the 0.9.4-4 version of the node-mongodb-native driver as there is a BAD bug in the binary bson type serialization/deserialization that will basically write corrupt objects to the db if you use the gridfs stuff.

Cheers

How to remove?

How does one remove in node-mongolian? Here's my attempt:

db.artists.remove {_id: req.body.id}, (err)->
    console.log err
    res.redirect '/admin'

But this does not do anything. Neither does it throw an error. It just passes through the documents on artists without removing the one with the given id. Now I realize that on mongo cl you must wrap the id with ObjectId() but is that true with mongolian? And if so, how?

Thank you for creating this. For me personally it has been far more usable than other mongo-targeted libraries I've tried for nodejs so far. I love that the basis is the mongo cl.

MapReduce

This might be a little much to ask at this point, but I don't suppose there is a way to run Map Reduce with mongolian is there?

collection.drop() and db.dropDatabase() not checking if callback is valid

If I fail to provide a callback function to drop() or dropDatabase() I get this error:

TypeError: undefined is not a function
at CALL_NON_FUNCTION (native)
at /home/qbert/devel/mongolian/lib/db.js:64:13
at /home/qbert/devel/mongolian/lib/util.js:19:18
at [object Object].next (/home/qbert/devel/mongolian/lib/cursor.js:159:9)
at /home/qbert/devel/mongolian/lib/cursor.js:163:18
at /home/qbert/devel/mongolian/lib/util.js:19:18
at Object. (/home/qbert/devel/mongolian/lib/cursor.js:117:9)
at Object.2 (/home/qbert/devel/mongolian/lib/util.js:19:18)
at [object Object]. (/home/qbert/devel/mongolian/lib/server.js:156:42)
at [object Object].emit (events.js:64:17)

Avoid creating multiple gridfiles with the same filename

Either make gridfs.create() asynchronous, or make gridfile.save() asynchronous and have it search for an existing file if it has no _id.

The former would make the programmer more aware of what's going on, while the latter can cleanly use the existing api.

How to find() items by _id

Using find( { _id: 'fabfba4db11fe35000000000' } ) seems not to be working , and I can find ObjectId anywhere so that I can say

find( { _id: ObjectId('fabfba4db11fe35000000000') } )

?

multi update

coll.updateAll({},{foo:1},function(){...}) reports success, but no changes are made. In real mongo shell, it would bark: "multi update only works with $ operators"

update: a light fix is to do if (multi && !newObj.$set) newObj = {$set: newObj} before composing mongo command in Collection#update

--Vladimir

Mongolian Timeout

I found out that, for some unknown situation when concurrency increased in node, mongolian couldn't communicate with mongodb (timeout occurred).
mongodb's health was fine so do node's health was also fine.
but after restarted node, it went back to work properly for some period of time, and the problem rose again.
I do load balance for 4 node instances, when mongolian of one instance was dead, the rest 3 were still fine and work properly. I though middleware got a communication problem with mongodb for some reason.

Anyway to track how this problem came from? is that because of some strange requests cause the single/shared mongolian object of that node instance went dead without returning error.

trying to save: Not an object

Everything goes well, I'm able to connect:

> var Mongolian = require('mongolian')
> var server = new Mongolian('example.com')
> [debug] mongo://example.com:27017: Connected
[debug] mongo://example.com:27017: Initialized as primary
[info] mongo://example.com:27017: Connected to primary
[debug] Finished scanning... primary? mongo://example.com:27017

> var db = server.db('wiki')
> var articles = db.collection('articles')

but then:

> articles.insert({attr2: 'yo!'})
Error: Not a valid object
at Function.serializeWithBufferAndIndex       (/Users/jeff/Projects/wiki/node_modules/mongolian/node_modules/mongodb/lib/mongodb/bson/bson.js:652:11)
at [object Object].toBinary (/Users/jeff/Projects/wiki/node_modules/mongolian/node_modules/mongodb/lib/mongodb/commands/insert_command.js:98:55)
at [object Object].send (/Users/jeff/Projects/wiki/node_modules/mongolian/node_modules/mongodb/lib/mongodb/connection.js:251:32)
at /Users/jeff/Projects/wiki/node_modules/mongolian/lib/server.js:260:20
at /Users/jeff/Projects/wiki/node_modules/mongolian/lib/util.js:19:18
at MongolianServer.cacher [as _connection] (/Users/jeff/Projects/wiki/node_modules/mongolian/node_modules/taxman/taxman.js:8:13)
at MongolianServer.sendCommand (/Users/jeff/Projects/wiki/node_modules/mongolian/lib/server.js:254:10)
at /Users/jeff/Projects/wiki/node_modules/mongolian/lib/server.js:148:17
at /Users/jeff/Projects/wiki/node_modules/mongolian/lib/util.js:19:18
at [object Object]._getPrimary (/Users/jeff/Projects/wiki/node_modules/mongolian/lib/server.js:115:35)

update n00b how-to

I am trying to update a record by the primary key. (I got insert and find working great, thank you!)

There are no examples or tests of update, save or findAndModify.

My code is, the id exists
tabCol.update({_id:'123121231'}
,{
stationName:'ha ha'
}
,false,false
,function(err,res) {
console.log(res);
});

It does not update when I look at mongo and it prints out undefined.
There should be an example of how to update by primary key.

2nd question is more mongo: When to use update vs findAndModify vs save, ex when 'updating' by pk.

tia,
Vic

Error after updating to 0.1.9

The error:

TypeError: Cannot set property 'maxListeners' of undefined
    at EventEmitter.setMaxListeners (events.js:12:29)
    at new <anonymous> (/Users/user/app/node_modules/mongolian/lib/server.js:81:22)

Disable log output

Is there a way to disable all console.log/info/error output? my log file is getting big... :-)

can't create server instance with [email protected]

├─┬ [email protected]
│ ├── [email protected]
│ ├── [email protected] extraneous
│ ├── [email protected]
│ └── [email protected]

in this case, when I useing new Mongolian, It occur undefined error. I think because monogb module version.

node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: undefined is not a function
at /Users/outsider/projects/nodejs/nodebook-examples/chapter-07/joinin-mongodb/node_modules/mongolian/lib/server.js:211:26
at MongolianServer.cacher as _connection
at MongolianServer.sendCommand (/Users/outsider/projects/nodejs/nodebook-examples/chapter-07/joinin-mongodb/node_modules/mongolian/lib/server.js:248:10)
at [object Object]. (/Users/outsider/projects/nodejs/nodebook-examples/chapter-07/joinin-mongodb/node_modules/mongolian/lib/server.js:51:20)
at [object Object].sendCommand (/Users/outsider/projects/nodejs/nodebook-examples/chapter-07/joinin-mongodb/node_modules/mongolian/lib/db.js:79:21)
at [object Object].nextBatch (/Users/outsider/projects/nodejs/nodebook-examples/chapter-07/joinin-mongodb/node_modules/mongolian/lib/cursor.js:135:17)
at [object Object].next (/Users/outsider/projects/nodejs/nodebook-examples/chapter-07/joinin-mongodb/node_modules/mongolian/lib/cursor.js:162:14)
at [object Object].findOne (/Users/outsider/projects/nodejs/nodebook-examples/chapter-07/joinin-mongodb/node_modules/mongolian/lib/collection.js:53:42)
at [object Object].runCommand (/Users/outsider/projects/nodejs/nodebook-examples/chapter-07/joinin-mongodb/node_modules/mongolian/lib/db.js:63:29)
at scanServer (/Users/outsider/projects/nodejs/nodebook-examples/chapter-07/joinin-mongodb/node_modules/mongolian/lib/server.js:53:21)

So, I change dependency module like this:

└─┬ [email protected]
├── [email protected]
├── [email protected] extraneous
├── [email protected]
└── [email protected]

It's working.

why scanning?

Although mongolian gets passed in the connection information

var mongo = new Mongolian('localhost:27017');

it prints

mongo://localhost:27017: Connected
mongo://localhost:27017: Initialized as primary
mongo://localhost:27017: Connected to primary
Finished scanning... primary? mongo://localhost:27017

which suggests it's searching for mongo. Why the scanning?

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.