|
代码比较通俗易懂,但是我还是在这个过程中浪费了不少时间,也算是看到了nodejs中异步的一个小坑。未来的坑还有很多,慢慢找坑填坑吧。
参考资料如下:
1、断言模块 : https://nodejs.org/api/assert.html
2、mongodb模块:https://github.com/mongodb/node-mongodb-native
废话不多说了,发完代码睡觉了,有兴趣的朋友可以持续关注本系列。
1 //加载nodejs中的mongodb模块
2 var MongoClient = require('mongodb').MongoClient;
3
4 //加载assert(断言模块)参考地址:https://nodejs.org/api/assert.html
5 var assert = require('assert');
6
7 // mongodb HOST地址 test表示当前所在的数据库
8 var url = 'mongodb://localhost:27017/test';
9 //启动mongodb服务,建立连接
10 MongoClient.connect(url, function(err, db) {
11 assert.equal(null, err);
12 console.log("Connected correctly to server");
13
14 //同步嵌套的写法
15 insertDocuments(db, function() {
16 updateDocument(db, function() {
17 deleteDocument(db, function() {
18 findDocuments(db, function() {
19 db.close();
20 });
21 });
22 });
23 });
24
25 //仔细观察同步与异步的CURD执行顺序。尝试在异步后添加db.close(); 思考为什么报错。
26 //异步的写法
27 // insertDocuments(db, function(){});
28 // updateDocument(db, function(){});
29 // deleteDocument(db, function(){});
30 // findDocuments(db, function(){});
31
32
33
34
35 });
36
37
38
39 //下面演示CURD的操作
40 var insertDocuments = function(db, callback) {
41 //得到文档集合
42 var collection = db.collection('rover');
43 //构造数据
44 var testData = [{a:1},{a:2},{a:3}];
45 //插入数据
46 collection.insertMany(testData, function(err, result) {
47 assert.equal(err, null);
48 assert.equal(3,result.result.n);
49 assert.equal(3,result.ops.length);
50 console.log('Inserted 3 Documents into the document collections');
51 callback(result);
52
53 });
54
55 };
56
57
58 //Updating a Documents 修改操作
59 var updateDocument = function(db, callback) {
60 //得到文档集合
61 var collection = db.collection('rover');
62 //修改文档集合
63 var update = {a:2};
64 var change = {$set:{a:5555}};
65 collection.updateOne(update,change, function(err, result) {
66 assert.equal(err,null);
67 assert.equal(1, result.result.n);
68 console.log("Updated the document with the field a equal to 2");
69 callback(result);
70 })
71 };
72
73 //Delete a document
74 var deleteDocument = function(db, callback) {
75 // Get the documents collection
76 var collection = db.collection('rover');
77 // Insert some documents
78 collection.deleteOne({ a : 3 }, function(err, result) {
79 assert.equal(err, null);
80 assert.equal(1, result.result.n);
81 console.log("Removed the document with the field a equal to 3");
82 callback(result);
83 });
84 };
85
86 //读取数据
87 var findDocuments = function(db, callback) {
88 // Get the documents collection
89 var collection = db.collection('rover');
90 // Find some documents
91 collection.find({}).toArray(function(err, docs) {
92 // assert.equal(err, null);
93 // assert.equal(2, docs.length);
94 console.log("Found the following records");
95 console.dir(docs);
96 callback(docs);
97 });
98 }; |
|
|