-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongo.js
More file actions
46 lines (35 loc) · 1.21 KB
/
mongo.js
File metadata and controls
46 lines (35 loc) · 1.21 KB
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
/**
* Expected output
* TODO: node mongo.js yourpassword Anna 040-1234556 -> added Anna number 040-1234556 to phonebook
* node mongo.js yourpassword -> fecth all contacts from database
*/
const mongoose = require('mongoose')
if ( process.argv.length<3 || process.argv[3] === '' || process.argv[4] === '') {
console.log('Either password, name or number is missing')
process.exit(1)
}
const password = process.argv[2]
const name = process.argv[3]
const number = process.argv[4]
const url = `mongodb+srv://admin:${password}@cluster0-sjxwf.mongodb.net/test?retryWrites=true&w=majority`
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
const phoneBookSchema = new mongoose.Schema({
name: String,
number: String
})
const Person = mongoose.model('person', phoneBookSchema)
if(process.argv.length == 3){
Person.find({}).then(result => {
console.log('Phonebook:')
result.forEach(person=> {
console.log(person.name +' '+ person.number)
})
mongoose.connection.close()
})
} else {
const person = new Person({ name, number })
person.save().then(result=>{
console.log(`Added ${result.name} ${result.number} to phonebook`)
mongoose.connection.close()
})
}