-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
80 lines (73 loc) · 1.91 KB
/
index.js
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
console.log("hello MongoDB");
const MongoDB = require("mongodb");
const MongoClient = MongoDB.MongoClient;
const url = "mongodb://localhost:27017";
const dbName = "xuesheng";
const client = new MongoClient(url, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const insertDocument = (db, cb) => {
const collection = db.collection("studentsInfo");
collection.insertMany(
[
{
name: "roy",
age: 27,
sex: "male",
home: "xi'an",
hobbies: ["NBA", "running", "history"]
},
{
name: "youling",
age: 25,
sex: "male",
home: "xi'an",
hobbies: ["reading", "sports"]
},
{
name: "zhen",
age: 27,
sex: "female",
home: "xian yang",
hobbies: ["tv", "music", "food"]
}
],
(err, result) => {
if (err) {
console.log("err", err);
return;
}
cb(result);
}
);
};
const indexCollection = (db, cb) => {
db.collection("studentsInfo").createIndex(
{
name: 1
},
null,
(err, result) => {
if (err) {
console.log("err", err);
return;
}
cb(result);
}
);
};
client.connect(err => {
if (err) return new Error("Connected failed to server!");
console.log("Connected successfully to server!");
const db = client.db(dbName);
console.log("db: ", db);
insertDocument(db, result => {
indexCollection(db, () => {
console.log("result", result);
// const indexes = db.getIndexes();
// console.log("indexes", indexes);
client.close();
});
});
});