How to learn: read it in detail and implement the relevant code manually
Learning Goals : This tutorial will teach you to install node, build servers, Express, MySQL, MongoDB, write background business logic, write interfaces, and finally complete a complete project backstage, a total of 10 days is expected.
node. js Operation Mangodb
Create a folder for placing today's files, NPM init initializes, and creates demo1.js for writing node code
Install the MongoDB control module to a local using NPM install MongoDB
Write the following operation code in Demo1.js
var mongo = require ("mongodb"); // Introduce the mongodb module
var assert = require ("assert"); // Introduce assertion module
var MongoClient = mongo.MongoClient; // Enable service
var Urls = "mongodb: // localhost: 27017 / demo2"; // url is stored in the connection pool.
MongoClient.connect (Urls, function (err, db) {// Get connection
assert.equal (null, err); // Use the assertion module instead of the previous if judgment
// Insert data
db.collection ("t1"). insert ({"name": "xiaoming"}, function (err, result) {// Connect to the database and pass in the collection with parameters
assert.equal (null, err);
console.log (result);
db.close ();
});
});
Code Explanation:
1 rows and 2 rows introduced the required two modules, 4 rows to open the server,
6 line is the address of the URL, the general default installation of the address and port is "mongodb://localhost:27017", the following Demo2 is the name of my MongoDB database (you replace the database you created)
8 rows are based on the URL declared above to establish a connection to the database, the Connect method has two parameters, 1, the connected database address, 2, callback function, two parameters of the callback function to send the error, and the correct case to return the database link, we can operate on this link.
Note: The link here is the place where beginners often error, if the error, to confirm the address and database name is wrong, make sure that their database has the corresponding library name.
Focus on the next 13 lines, here is the operation of node insert database, db.collection ("T1") means to get the table that needs operation, insert is Insert method, method receives two parameters, 1, insert content, 2, callback function, callback function two parameters indicate send error, And the results returned in the correct case.
15 Line Print error results, 16 lines close and Database link (if the browser crashes)
Execute demo1.js. Successful results are obtained (n of the dash indicates success 1)
Querying the database, you can see the newly added data
Look up: The Find method, the JSON passed in to find the filter (if not passed, query all), after the toarray is to manipulate the data into an array format we can recognize
The remainder of the operation, in addition to the central data manipulation section of the code, the rest of the code is the same.
var mongo = require ("mongodb"); // Introduce the mongodb module
var assert = require ("assert"); // Introduce assertion module
var MongoClient = mongo.MongoClient; // Enable service
var Urls = "mongodb: // localhost: 27017 / demo2"; // url is stored in the connection pool.
MongoClient.connect (Urls, function (err, db) {// Get connection
assert.equal (null, err); // Use the assertion module instead of the previous if judgment
// Find data
db.collection ("t1"). find ({"name": "xiaoming"}). toArray (function (err, result) {
assert.equal (null, err);
console.log (result);
db.close ();
})
});
Run, successfully finds the data inserted in the previous step
Delete using Deleteone to delete a piece of data, two parameter 1, delete lookup JSON 2, callback function
var mongo = require ("mongodb"); // Introduce the mongodb module
var assert = require ("assert"); // Introduce assertion module
var MongoClient = mongo.MongoClient; // Enable service
var Urls = "mongodb: // localhost: 27017 / demo2"; // url is stored in the connection pool.
MongoClient.connect (Urls, function (err, db) {// Get connection
assert.equal (null, err); // Use the assertion module instead of the previous if judgment
//delete data
db.collection ("t1"). deleteOne ({"name": "xiaoming"}, function (err, result) {// Connect to the database and pass in the collection with parameters
assert.equal (null, err);
console.log (result);
db.close ();
});
});
execution, the result of success
Query database Discovery xiaoming that data was deleted.
Modified: Using the Update method, including three parameters, 1, query criteria, 2, modified fields and modifiers, 3, callback function
var mongo = require ("mongodb"); // Introduce the mongodb module
var assert = require ("assert"); // Introduce assertion module
var MongoClient = mongo.MongoClient; // Enable service
var Urls = "mongodb: // localhost: 27017 / demo2"; // url is stored in the connection pool.
MongoClient.connect (Urls, function (err, db) {// Get connection
assert.equal (null, err); // Use the assertion module instead of the previous if judgment
//change the data
db.collection ("t1"). update ({"name": "zhangsan1"}, {$ set: {"name": "xiaoming"}}, function (err, result) {// connect to the database, And pass the collection with parameters
assert.equal (null, err);
console.log (result);
db.close ();
});
});
Results of successful operation
Querying the database found that the original zhangsan1 was modified into a xiaoming
Here, the implementation of the Nodejs additions and deletions to search the MongoDB database
Package additions and deletions to the code
Create an encapsulated JS file Dbhandler.js, assign the following code (the encapsulated code text is too difficult to explain here)--Note: The 6th line of the URL after the database replaced with the database they want to operate, the other does not have to change
var mongo = require ("mongodb"); // @ 2.2.11
var MongoClient = mongo.MongoClient;
var assert = require ('assert');
var host = "localhost";
var port = "27017";
var Urls = 'mongodb: // localhost: 27017 / demo2';
// add a piece of data
var add = function (db, collections, selector, fn) {
var collection = db.collection (collections);
collection.insertMany ([selector], function (err, result) {
assert.equal (err, null);
fn (result);
db.close ();
});
}
// delete
var deletes = function (db, collections, selector, fn) {
var collection = db.collection (collections);
collection.deleteOne (selector, function (err, result) {
try {assert.equal (err, null)} catch (e) {
console.log (e);
}
fn (result);
db.close ();
});
};
// find
var find = function (db, collections, selector, fn) {
var collection = db.collection (collections);
collection.find (selector) .toArray (function (err, docs) {
try {
assert.equal (err, null);
} catch (e) {
console.log (e);
docs = [];
}
fn (docs);
db.close ();
});
}
// (Permission Control)-temporarily useless
MongoClient.connect (Urls, function (err, db) {
find (db, "powers", null, function (d) {
console.log ("123s");
console.log (d.length);
});
});
// update
var updates = function (db, collections, selector, fn) {
var collection = db.collection (collections);
console.log (selector);
collection.updateOne (selector [0], selector [1], function (err, result) {
assert.equal (err, null);
assert.equal (1, result.result.n);
fn (result);
db.close ();
});
}
// Methods are assigned to the operation object for easy invocation
var methodType = {
login: find,
show: find,
add: add,
getpower: find,
update: updates,
delete: deletes,
updatepass: updates,
adduser: add,
usershow: find,
getcategory: find,
getcourse: find,
find: find,
state: find,
top: find,
AddDirectory: find,
updateDirectory: updates,
deleteDirectory: deletes,
showlist: find,
showdir: find
};
// Main logic
module.exports = function (req, res, collections, selector, fn) {
MongoClient.connect (Urls, function (err, db) {
assert.equal (null, err);
console.log ("Connected correctly to server");
methodType [req.query.action] (db, collections, selector, fn);
db.close ();
});
};
Use this package
Specific package usage, we will introduce in the next lesson project
Let's talk about it today, tomorrow we will explain: project creation, background data request interface writing
node. js 0 Basic Detailed tutorial (7): node. js operation MongoDB, and how to package