Home > Article > Web Front-end > Implementation of connecting to mongodb database using Nodejs
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!