2

Just looking at sample code from mongodb driver: http://mongodb.github.io/node-mongodb-native/2.2/tutorials/projections/

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  findDocuments(db, function() {
    db.close();
  });  
});


var findDocuments = function(db, callback) {
  // Get the documents collection
  var collection = db.collection( 'restaurants' );
// Find some documents
  collection.find({ 'cuisine' : 'Brazilian' }, { 'name' : 1, 'cuisine' : 1 }).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log("Found the following records");
    console.log(docs)
    callback(docs);
  });
}

Shouln't last line callback(docs) be callback(null, docs) ?

1
  • According node.js callback notation it should, but developer could use own style. In this style, callback doesn't accept error at all. Commented Aug 3, 2017 at 16:00

1 Answer 1

2

It depends on your callback.

There are error-first callbacks, which do take an error as the first argument, and the data as the second argument, like in: callback (err, data)

However, in Mongo's official example webpage (the one you pointed out), they pass a callback without an error argument. Error-first callbacks are everywhere inside Node's built-in modules, but Node does NOT enforce you, by any means, to use them. That's what, in this example, Mongo developers decided to do.

You can easily re-write the Mongo example to use an error-first callback, though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.