Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

The official MongoDB Node.js driver

License

NotificationsYou must be signed in to change notification settings

mongodb/node-mongodb-native

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

The officialMongoDB driver for Node.js.

Upgrading to version 6? Take a look at ourupgrade guide here!

Quick Links

SiteLink
Documentationwww.mongodb.com/docs/drivers/node
API Docsmongodb.github.io/node-mongodb-native
npm packagewww.npmjs.com/package/mongodb
MongoDBwww.mongodb.com
MongoDB Universitylearn.mongodb.com
MongoDB Developer Centerwww.mongodb.com/developer
Stack Overflowstackoverflow.com
Source Codegithub.com/mongodb/node-mongodb-native
Upgrade to v6etc/notes/CHANGES_6.0.0.md
ContributingCONTRIBUTING.md
ChangelogHISTORY.md

Release Integrity

Releases are created automatically and signed using theNode team's GPG key. This applies to the git tag as well as all release packages provided as part of a GitHub release. To verify the provided packages, download the key and import it using gpg:

gpg --import node-driver.asc

The GitHub release contains a detached signature file for the NPM package (namedmongodb-X.Y.Z.tgz.sig).

The following command returns the link npm package.

npm view mongodb@vX.Y.Z dist.tarball

Using the result of the above command, acurl command can return the official npm package for the release.

To verify the integrity of the downloaded package, run the following command:

gpg --verify mongodb-X.Y.Z.tgz.sig mongodb-X.Y.Z.tgz

Note

No verification is done when using npm to install the package. The contents of the Github tarball and npm's tarball are identical.

The MongoDB Node.js driver followssemantic versioning for its releases.

Bugs / Feature Requests

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

Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and theCore Server (i.e. SERVER) project arepublic.

Support / Feedback

For issues with, questions about, or feedback for the Node.js driver, please look into oursupport channels. Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on theMongoDB Community Forums.

Change Log

Change history can be found inHISTORY.md.

Compatibility

The driver currently supports 4.2+ servers.

For exhaustive server and runtime version compatibility matrices, please refer to the following links:

Component Support Matrix

The following table describes add-on component version compatibility for the Node.js driver. Only packages with versions in these supported ranges are stable when used in combination.

Componentmongodb@3.xmongodb@4.xmongodb@5.xmongodb@<6.12mongodb@>=6.12
bson^1.0.0^4.0.0^5.0.0^6.0.0^6.0.0
bson-ext^1.0.0 || ^2.0.0^4.0.0N/AN/AN/A
kerberos^1.0.0^1.0.0 || ^2.0.0^1.0.0 || ^2.0.0^2.0.1^2.0.1
mongodb-client-encryption^1.0.0^1.0.0 || ^2.0.0^2.3.0^6.0.0^6.0.0
mongodb-legacyN/A^4.0.0^5.0.0^6.0.0^6.0.0
@mongodb-js/zstdN/A^1.0.0^1.0.0^1.1.0^1.1.0 || ^2.0.0

Typescript Version

We recommend using the latest version of typescript, however we currently ensure the driver's public types compile againsttypescript@4.4.0.This is the lowest typescript version guaranteed to work with our driver: older versions may or may not work - use at your own risk.Since typescriptdoes not restrict breaking changes to major versions, we consider this support best effort.If you run into any unexpected compiler failures against our supported TypeScript versions, please let us know by filing an issue on ourJIRA.

Additionally, our Typescript types are compatible with the ECMAScript standard for our minimum supported Node version. Currently, our Typescript targets es2021.

Installation

The recommended way to get started using the Node.js 5.x driver is by using thenpm (Node Package Manager) to install the dependency in your project.

After you've created your own project usingnpm init, you can run:

npm install mongodb

This will download the MongoDB driver and add a dependency entry in yourpackage.json file.

If you are a Typescript user, you will need the Node.js type definitions to use the driver's definitions:

npm install -D @types/node

Driver Extensions

The MongoDB driver can optionally be enhanced by the following feature packages:

Maintained by MongoDB:

Some of these packages include native C++ extensions.Consult thetrouble shooting guide here if you run into compilation issues.

Third party:

Quick Start

This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see theofficial documentation.

Create thepackage.json file

First, create a directory where your application will live.

mkdir myProjectcd myProject

Enter the following command and answer the questions to create the initial structure for your new project:

npm init -y

Next, install the driver as a dependency.

npm install mongodb

Start a MongoDB Server

For complete MongoDB installation instructions, seethe manual.

  1. Download the right MongoDB version fromMongoDB
  2. Create a database directory (in this case under/data).
  3. Install and start amongod process.
mongod --dbpath=/data

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

Connect to MongoDB

Create a newapp.js file and add the following code to try out some basic CRUDoperations using the MongoDB driver.

Add code to connect to the server and the databasemyProject:

NOTE: Resolving DNS Connection issues

Node.js 18 changed the default DNS resolution ordering from always prioritizing IPv4 to the orderingreturned by the DNS provider. In some environments, this can result inlocalhost resolving toan IPv6 address instead of IPv4 and a consequent failure to connect to the server.

This can be resolved by:

  • specifying the IP address family using the MongoClientfamily option (MongoClient(<uri>, { family: 4 } ))
  • launching mongod or mongos with the ipv6 flag enabled (--ipv6 mongod option documentation)
  • using a host of127.0.0.1 in place of localhost
  • specifying the DNS resolution ordering with the--dns-resolution-order Node.js command line argument (e.g.node --dns-resolution-order=ipv4first)
const{ MongoClient}=require('mongodb');// or as an es module:// import { MongoClient } from 'mongodb'// Connection URLconsturl='mongodb://localhost:27017';constclient=newMongoClient(url);// Database NameconstdbName='myProject';asyncfunctionmain(){// Use connect method to connect to the serverawaitclient.connect();console.log('Connected successfully to server');constdb=client.db(dbName);constcollection=db.collection('documents');// the following code examples can be pasted here...return'done.';}main().then(console.log).catch(console.error).finally(()=>client.close());

Run your app from the command line with:

node app.js

The application should printConnected successfully to server to the console.

Insert a Document

Add toapp.js the following function which uses theinsertManymethod to add three documents to thedocuments collection.

constinsertResult=awaitcollection.insertMany([{a:1},{a:2},{a:3}]);console.log('Inserted documents =>',insertResult);

TheinsertMany command returns an object with information about the insert operations.

Find All Documents

Add a query that returns all the documents.

constfindResult=awaitcollection.find({}).toArray();console.log('Found documents =>',findResult);

This query returns all the documents in thedocuments collection.If you add this below the insertMany example, you'll see the documents you've inserted.

Find Documents with a Query Filter

Add a query filter to find only documents which meet the query criteria.

constfilteredDocs=awaitcollection.find({a:3}).toArray();console.log('Found documents filtered by { a: 3 } =>',filteredDocs);

Only the documents which match'a' : 3 should be returned.

Update a document

The following operation updates a document in thedocuments collection.

constupdateResult=awaitcollection.updateOne({a:3},{$set:{b:1}});console.log('Updated documents =>',updateResult);

The method updates the first document where the fielda is equal to3 by adding a new fieldb to the document set to1.updateResult contains information about whether there was a matching document to update or not.

Remove a document

Remove the document where the fielda is equal to3.

constdeleteResult=awaitcollection.deleteMany({a:3});console.log('Deleted documents =>',deleteResult);

Index a Collection

Indexes can improve your application'sperformance. The following function creates an index on thea field in thedocuments collection.

constindexName=awaitcollection.createIndex({a:1});console.log('index name =',indexName);

For more detailed information, see theindexing strategies page.

Error Handling

If you need to filter certain errors from our driver, we have a helpful tree of errors described inetc/notes/errors.md.

It is our recommendation to useinstanceof checks on errors and to avoid relying on parsingerror.message anderror.name strings in your code.We guaranteeinstanceof checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.

Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release.This meansinstanceof will always be able to accurately capture the errors that our driver throws.

constclient=newMongoClient(url);awaitclient.connect();constcollection=client.db().collection('collection');try{awaitcollection.insertOne({_id:1});awaitcollection.insertOne({_id:1});// duplicate key error}catch(error){if(errorinstanceofMongoServerError){console.log(`Error worth logging:${error}`);// special case for some reason}throwerror;// still want to crash}

Nightly releases

If you need to test with a change from the latestmain branch, ourmongodb npm package has nightly versions released under thenightly tag.

npm install mongodb@nightly

Nightly versions are published regardless of testing outcome.This means there could be semantic breakages or partially implemented features.The nightly build is not suitable for production use.

Next Steps

License

Apache 2.0

© 2012-present MongoDBContributors
© 2009-2012 Christian Amor Kvalheim


[8]ページ先頭

©2009-2025 Movatter.jp