Socket
Socket
Sign inDemoInstall

mongodb-core

Package Overview
Dependencies
3
Maintainers
3
Versions
177
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

mongodb-core


Version published
Maintainers
3
Created

Package description

What is mongodb-core?

The mongodb-core package is a low-level driver for MongoDB that provides the core functionality for interacting with MongoDB databases. It is used internally by the higher-level mongodb package but can be used directly for more fine-grained control over MongoDB operations.

What are mongodb-core's main functionalities?

Connecting to MongoDB

This feature allows you to establish a connection to a MongoDB server. The code sample demonstrates how to create a new MongoClient instance and connect to a MongoDB server running on localhost.

const MongoClient = require('mongodb-core').MongoClient;
const client = new MongoClient('mongodb://localhost:27017');
client.connect((err) => {
  if (err) throw err;
  console.log('Connected to MongoDB');
  client.close();
});

Performing CRUD Operations

This feature allows you to perform CRUD (Create, Read, Update, Delete) operations on a MongoDB database. The code sample demonstrates how to insert a document into a collection.

const MongoClient = require('mongodb-core').MongoClient;
const client = new MongoClient('mongodb://localhost:27017');
client.connect((err) => {
  if (err) throw err;
  const db = client.db('test');
  const collection = db.collection('documents');
  collection.insertOne({ a: 1 }, (err, result) => {
    if (err) throw err;
    console.log('Document inserted');
    client.close();
  });
});

Handling Replication

This feature allows you to handle MongoDB replication. The code sample demonstrates how to connect to a MongoDB replica set.

const ReplSet = require('mongodb-core').ReplSet;
const replSet = new ReplSet([{ host: 'localhost', port: 27017 }], { setName: 'rs0' });
replSet.on('connect', () => {
  console.log('Connected to replica set');
  replSet.destroy();
});
replSet.connect();

Other packages similar to mongodb-core

Changelog

Source

3.1.1 (2018-08-13)

Bug Fixes

  • auth: prevent stalling on authentication when connected (6b4ac89)
  • buffer: replace deprecated Buffer constructor (7c71e19)
  • commands: check doc.cursor errors (4f2b263)
  • cursor: check for session presence independently (7c76c62)
  • cursor: check for sessions independently in core cursor (cb5df28)
  • cursor: typo in _find() (95f7fd2)
  • error: attach command response to MongoWriteConcernError (#322) (24c5d06)
  • getmore-killcursor: slaveOk shall not be included on these (40fb2f4)
  • kerberos: loosen restrictions on kerberos versions (c4add26)
  • mongos: use incrementTransactionNumber directly on session (e230d54)
  • pool: ensure that lsid is sent in get requests to mongos (ae820f6)
  • read-preference: correct server sort for nearest selection (dd4eb9a)
  • sdam: we can't use Array.includes yet (9c3b5ab)
  • server: correct typo using this instead of server (c54f040)
  • sessions: add toBSON method to ClientSession (d95a4d1)
  • sessions: never send endSessions from a ClientSession (05ffe82)
  • topology-description: we can't use Object.values yet (91df350)
  • transactions: do not send txnNumber for non-write commands (#308) (eb67b1a)
  • uri_parser: ensure default port is 27017 (426a95e)
  • uri-parser: Incorrect parsing of arrays (fcff104)
  • uri-parser: Parse comma separated option values (2dd1de0)
  • wireprotocol: only send bypassDocumentValidation if true (a81678b)

Features

  • auth: adds saslprep and SCRAM-SHA-256 (506c087)
  • cursor: implement cursor for new sdam implementation (f289226)
  • cursor: store operation time from initial query (55e761e)
  • error: add more specific error type for write concern errors (347c5d7)
  • Error: adding error metadata field (33be560)
  • kerberos: expose warning for kerberos mismatch versions (efc0e43)
  • max-staleness: properly support a max staleness reducer (d9c5c16)
  • MongoTimeoutError: add common class for timeout events (c5b4752)
  • monitoring: add support for server monitoring to Server (30a394d)
  • op-compressed: add support for OP_COMPRESSED to new sdam impl (8deec9b)
  • retryableWrites: adding more support for retries (d4c1597)
  • sdam-monitoring: add basic monitoring for new Topology type (bb0c522)
  • server: add command support to new server class (d9a8c05)
  • server-selection: add basic support for server selection (ccc5e1d)
  • topology: introduce a single Topology type, and test runner (f35d773)
  • topology-description: add helper method for server ownership (2c64c75)
  • txns: add initial transaction interface for sessions (ed76be0)

<a name="3.1.0"></a>

Readme

Source

Build Status Coverage Status

Description

The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication.

MongoDB Node.JS Core Driver

whatwhere
documentationhttp://mongodb.github.io/node-mongodb-native/
apidochttp://mongodb.github.io/node-mongodb-native/
sourcehttps://github.com/mongodb-js/mongodb-core
mongodbhttp://www.mongodb.org/

Blogs of Engineers involved in the driver

Bugs / Feature Requests

Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a case in our issue management tool, JIRA:

Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the Core Server (i.e. SERVER) project are public.

Questions and Bug Reports

Change Log

http://jira.mongodb.org/browse/NODE

QuickStart

The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials.

Create the package.json file

Let's create a directory where our application will live. In our case we will put this under our projects directory.

mkdir myproject
cd myproject

Create a package.json using your favorite text editor and fill it in.

{
  "name": "myproject",
  "version": "1.0.0",
  "description": "My first project",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "git://github.com/christkv/myfirstproject.git"
  },
  "dependencies": {
    "mongodb-core": "~1.0"
  },
  "author": "Christian Kvalheim",
  "license": "Apache 2.0",
  "bugs": {
    "url": "https://github.com/christkv/myfirstproject/issues"
  },
  "homepage": "https://github.com/christkv/myfirstproject"
}

Save the file and return to the shell or command prompt and use NPM to install all the dependencies.

npm install

You should see NPM download a lot of files. Once it's done you'll find all the downloaded packages under the node_modules directory.

Booting up a MongoDB Server

Let's boot up a MongoDB server instance. Download the right MongoDB version from MongoDB, open a new shell or command line and ensure the mongod command is in the shell or command line path. Now let's create a database directory (in our case under /data).

mongod --dbpath=/data --port 27017

You should see the mongod process start up and print some status information.

Connecting to MongoDB

Let's create a new app.js file that we will use to show the basic CRUD operations using the MongoDB driver.

First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection.

var Server = require('mongodb-core').Server
  , assert = require('assert');

// Set up server connection
var server = new Server({
    host: 'localhost'
  , port: 27017
  , reconnect: true
  , reconnectInterval: 50
});

// Add event listeners
server.on('connect', function(_server) {
  console.log('connected');
  test.done();
});

server.on('close', function() {
  console.log('closed');
});

server.on('reconnect', function() {
  console.log('reconnect');
});

// Start connection
server.connect();

To connect to a replicaset we would use the ReplSet class and for a set of Mongos proxies we use the Mongos class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations.

var Server = require('mongodb-core').Server
  , assert = require('assert');

// Set up server connection
var server = new Server({
    host: 'localhost'
  , port: 27017
  , reconnect: true
  , reconnectInterval: 50
});

// Add event listeners
server.on('connect', function(_server) {
  console.log('connected');

  // Execute the ismaster command
  _server.command('system.$cmd', {ismaster: true}, function(err, result) {

    // Perform a document insert
    _server.insert('myproject.inserts1', [{a:1}, {a:2}], {
      writeConcern: {w:1}, ordered:true
    }, function(err, results) {
      assert.equal(null, err);
      assert.equal(2, results.result.n);      

      // Perform a document update
      _server.update('myproject.inserts1', [{
        q: {a: 1}, u: {'$set': {b:1}}
      }], {
        writeConcern: {w:1}, ordered:true
      }, function(err, results) {
        assert.equal(null, err);
        assert.equal(1, results.result.n);

        // Remove a document
        _server.remove('myproject.inserts1', [{
          q: {a: 1}, limit: 1
        }], {
          writeConcern: {w:1}, ordered:true
        }, function(err, results) {
          assert.equal(null, err);
          assert.equal(1, results.result.n);

          // Get a document
          var cursor = _server.cursor('integration_tests.inserts_example4', {
              find: 'integration_tests.example4'
            , query: {a:1}
          });

          // Get the first document
          cursor.next(function(err, doc) {
            assert.equal(null, err);
            assert.equal(2, doc.a);

            // Execute the ismaster command
            _server.command("system.$cmd"
              , {ismaster: true}, function(err, result) {
                assert.equal(null, err)
                _server.destroy();              
            });
          });
      });
    });

    test.done();
  });
});

server.on('close', function() {
  console.log('closed');
});

server.on('reconnect', function() {
  console.log('reconnect');
});

// Start connection
server.connect();

The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands.

  • insert, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order.
  • update, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order.
  • remove, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order.
  • cursor, Returns you a cursor for either the 'virtual' find command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage.
  • command, Executes a command against MongoDB and returns the result.
  • auth, Authenticates the current topology using a supported authentication scheme.

The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction.

Next steps

The next step is to get more in depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information.

Keywords

FAQs

Last updated on 13 Aug 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc