Nodejs:使用Mongodb存储和提供后端CRD服务

<table class="text"><tr class="li1">
<td class="ln"><pre class="de1">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

show dbs     local           0.000GB   创建一个数据库       use todos     (若database不存在,则会创建一个,此时若不做任何操作直接退出,则MongoDB会删除该数据库)       db.todos.insert({id:1,name:"reco"})     db.todos.insert({id:2,name:"rita"})   查询 :       db.todos.find()       { "_id" : ObjectId("5b727c0846b6c71a98d3af52"),"id" : 1,"name" : "reco" }     { "_id" : ObjectId("5b727c7046b6c71a98d3af53"),"id" : 2,"name" : "reta" }   删除记录:       db.todo.remove({id:1})     删除数据库       db.todo.drop()     ## 使用nodejs方式访问Mongodb   使用nodejs执行类似Shell对对象的CRD,代码如下:       var MongoClient = require('mongodb').MongoClient;     var url = "mongodb://localhost:27017/todos";     MongoClient.connect(url,function(err,db) {       if (err) throw err;       console.log("Database created!");       var dbo = db.db("todos");       // var myobj = { id: 1,name: "reco" };       // dbo.collection("todo").insertOne(myobj,res) {       //   if (err) throw err;       //   console.log("1 document inserted");       //   db.close();       // });        var myobj = [         { id: 1,name: 'reco'},        { id: 2,name: 'rita'},      ];       dbo.collection("todo").insertMany(myobj,res) {         if (err) throw err;         console.log("Number of documents inserted: " + res.insertedCount);         dbo.collection("todo").find({}).toArray(function(err,result) {             if (err) throw err;             console.log(result);               var myquery = { id: 1 };                   dbo.collection("todo").deleteMany(myquery,obj) {                     if (err) throw err;                     console.log("document deleted");                     db.close();                   });           });           });     })   代码非常简单,无需更多解释。此代码使用了mongodb模块,需要首先安装:         npm init -y     npm i mongodb --save     然后使用`node index.js`运行即可看到效果:       Database created!     Number of documents inserted: 2     [ { _id: 5b72ab9e3245f169ef5f43d2,id: 1,name: 'reco' },      { _id: 5b72ab9e3245f169ef5f43d3,id: 2,name: 'rita' } ]     document deleted   ## 利用高级异步特性   使用Await/Async特性,可以有效的减少代码中的回调地狱现象。同样的功能,可以使用这样的代码:       const MongoClient = require('mongodb').MongoClient;     const connectionString = 'mongodb://localhost:27017';     (async () => {         const client = await MongoClient.connect(connectionString,            { useNewUrlParser: true });         const dbo = client.db('todos');         try {            var res = await dbo.collection('todo').insertMany(                 [{id:1,name:"reco"},{id:2,name:"rita"}]);            console.log("Number of documents inserted: " + res.insertedCount);            var r = await dbo.collection("todo").find().toArray()            console.log(r);            var myquery = { id: 1 };            var r = await dbo.collection("todo").deleteMany(myquery)            console.log("document deleted");         }         finally {             client.close();         }     })().catch(err => console.error(err));     执行此代码,输出如下:       Number of documents inserted: 2     [ { _id: 5b72ae8a1c674a6ac1c5aa6e,      { _id: 5b72ae8a1c674a6ac1c5aa6f,name: 'rita' } ]     document deletedNodejs:使用Mongodb存储和提供后端CRD服务

相关文章

文章浏览阅读552次。com.mongodb.MongoQueryException: Quer...
文章浏览阅读635次,点赞9次,收藏8次。MongoDB 是一种 NoSQ...
文章浏览阅读2.1k次。和。_mongodb 日期类型
文章浏览阅读1.7k次。Scalestack等客户期待使用MongoDB Atla...
文章浏览阅读970次。SpringBoot整合中间件mongodb、ES_sprin...
文章浏览阅读673次。MongoDB 简介_尚医通sql