-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo.js
53 lines (41 loc) · 1.31 KB
/
mongo.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
const mongoose = require('mongoose')
if (process.argv.length < 3 || process.argv.length > 5) {
console.log('Invalid parameters count');
}
const password = process.argv[2];
const url = `mongodb+srv://admin:${password}@cluster01-fullstackopen.dksmkwb.mongodb.net/phonebook?retryWrites=true&w=majority`;
mongoose.set('strictQuery', false);
mongoose.connect(url).
catch(err => {
console.error('Connection to database failed');
console.log(err.message);
process.exit(1);
})
const contactSchema = new mongoose.Schema({
name: String,
number: String,
})
const Address = mongoose.model('contact', contactSchema);
if(process.argv.length === 5) {
addContact();
} else if(process.argv.length === 3) {
getAllContacts();
}
function addContact() {
const name = process.argv[3];
const number = process.argv[4];
const newAddress = new Address({name, number});
newAddress.save().then(result => {
console.log(`Added '${result.name}: ${result.number}' to contacts`);
mongoose.connection.close();
})
}
function getAllContacts() {
Address.find({}).then(result => {
console.log('phonebook:');
result.forEach(contact => {
console.log(`${contact.name} ${contact.number}`);
})
mongoose.connection.close();
})
}