-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongo.js
More file actions
57 lines (46 loc) · 1.29 KB
/
mongo.js
File metadata and controls
57 lines (46 loc) · 1.29 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
47
48
49
50
51
52
53
54
55
56
57
require('dotenv').config()
const mongoose = require('mongoose')
const { Schema } = mongoose
const url = process.env.MONGODB_URI
const firstName = process.argv[2]
const phoneNumber = Number(process.argv[3])
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true })
.then(result => console.log('connected to MongoDB'))
.catch(error => console.log('error connecting to MongoDB', error.message))
// Schemas
const personSchema = new Schema({
firstName: String,
phoneNumber: Number,
})
// Model
const Person = mongoose.model('Person', personSchema)
// Functions
const getPersons = () => {
Person.find({})
.then(result => {
console.log('phonebook:')
result.forEach(person => {
console.log(person.firstName, person.phoneNumber)
})
mongoose.connection.close()
})
}
const createPerson = () => {
const person = new Person({
firstName: firstName,
phoneNumber: phoneNumber
})
person
.save().then(result => {
console.log(result)
console.log(`added ${firstName} number ${phoneNumber} to phonebook`)
mongoose.connection.close()
})
.catch(error => console.log(error))
}
if (process.argv.length === 2) {
getPersons()
}
if (process.argv.length === 4) {
createPerson()
}