This article mainly introduces the implementation code of using Nodejs to connect to the mongodb database. Friends who need it can refer to
A simple example of nodejs connecting to mongodb, from the mongodb official example
1. Create package.json
First, create our project directory connect-mongodb and use it as our current directory
mkdir connect-mongodb cd connect-mongodb
Enter the npm init
command to create package.json
npm init
Then, install mongodb's nodejs version driver
npm install mongodb --save
mongodb driver package will be installed into node_modules in the current directory
2 . Start the MongoDB server
Install MongoDB and start the MongoDB database service. Please refer to my previous article, or the official MongoDB documentation
3. Connection MongoDB
Create an app.js file and add the following code to connect to the database named myNewDatabase on the server address 192.168.0.243 and the mongodb port 27017
var MongoClient = require('mongodb').MongoClient, assert = require('assert'); // Connection URL var url = 'mongodb://192.168.0.243:27017/myNewDatabase'; MongoClient.connect(url,function(err,db){ assert.equal(null,err); console.log("Connection successfully to server"); db.close(); });
Enter the following command on the command line to run app.js
node app.js
4. Insert Documents
Add the following code in app.js and use the insertMany method to add 3 documents to the documents collection
var insertDocuments = function(db, callback){ // get ths documents collection var collection = db.collection('documents'); // insert some documents collection.insertMany([ {a:1},{a:2},{a:3} ],function(err,result){ assert.equal(err,null); assert.equal(3,result.result.n); assert.equal(3,result.ops.length); console.log("Inserted 3 documents into the collection"); callback(result); }); };
insert command returns an object containing the following attributes:
result Document result returned by MongoDB
ops Document with _id field added
connection The connection used to perform the insert operation
Update the following code in app.js to call the insertDocuments method
var MongoClient = require('mongodb').MongoClient , assert = require('assert'); // Connection URL var url = 'mongodb://localhost:27017/myproject'; // Use connect method to connect to the server MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected successfully to server"); insertDocuments(db, function() { db.close(); }); });
Use node app.js to run in the command line
5. Query all documents
Add the findDocuments function
var findDocuments = function(db,callback){ // get the documents collection var collection = db.collection('documents'); // find some documents collection.find({}).toArray(function(err,docs){ assert.equal(err,null); console.log("Found the following records"); console.log(docs); callback(docs); }); };
The findDocuments function queries all documents in all 'documents' collections and adds this function to the callback function of MongoClient.connect
var MongoClient = require('mongodb').MongoClient , assert = require('assert'); // Connection URL var url = 'mongodb://localhost:27017/myproject'; // Use connect method to connect to the server MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to server"); insertDocuments(db, function() { findDocuments(db, function() { db.close(); }); }); });
6. Query documents using query filter
Query 'a' :3’s documentation
var findDocuments = function(db, callback) { // Get the documents collection var collection = db.collection('documents'); // Find some documents collection.find({'a': 3}).toArray(function(err, docs) { assert.equal(err, null); console.log("Found the following records"); console.log(docs); callback(docs); }); }
7. Update documentation
var updateDocument = function(db,callback){ // get the documents collection var collection = db.collection('documents'); // update document where a is 2, set b equal to 1 collection.updateOne({a:2},{ $set:{b:1} },function(err,result){ assert.equal(err,null); assert.equal(1,result.result.n); console.log("updated the document with the field a equal to 2"); callback(result); }); };
The updateDocument method updates the first document that meets the condition a is 2, adds a b attribute, and sets it to 1.
Add the updateDocument method to the callback of the MongoClient.connect method
MongoClient.connect(url,function(err,db){ assert.equal(null,err); console.log("Connection successfully to server"); insertDocuments(db,function(){ updateDocument(db,function(){ db.close(); }); }); });
8. Delete the document
var removeDocument = function(db,callback){ // get the documents collection var collection = db.collection('documents'); // remove some documents collection.deleteOne({a:3},function(err,result){ assert.equal(err,null); assert.equal(1,result.result.n); console.log("removed the document with the field a equal to 3"); callback(result); }); };
Add to app.js
var MongoClient = require('mongodb').MongoClient , assert = require('assert'); // Connection URL var url = 'mongodb://localhost:27017/myproject'; // Use connect method to connect to the server MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected successfully to server"); insertDocuments(db, function() { updateDocument(db, function() { removeDocument(db, function() { db.close(); }); }); }); });
9. Create indexes
Indexes can improve application performance. Below your code adds an index on the 'a' attribute
var indexCollection = function(db,callback){ db.collection('documents').createIndex({ a:1 },null,function(err,results){ console.log(results); callback(); }); };
Update app.js
MongoClient.connect(url,function(err,db){ assert.equal(null,err); console.log("Connection successfully to server"); insertDocuments(db,function(){ indexCollection(db,function(){ db.close(); }); }); });
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Methods to prevent SQL injection in node-mysql
NodeJs form-data format transfer file method
The above is the detailed content of Implementation of connecting to mongodb database using Nodejs. For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor
