forked from sohamkamani/node-express-mongo-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
28 lines (21 loc) · 723 Bytes
/
db.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
const { MongoClient, ObjectId } = require('mongodb')
const connectionUrl = 'mongodb://mongo:27017'
const dbName = 'store'
let db
const init = () =>
MongoClient.connect(connectionUrl, { useNewUrlParser: true }).then((client) => {
db = client.db(dbName)
})
const insertItem = (item) => {
const collection = db.collection('items')
return collection.insertOne(item)
}
const getItems = () => {
const collection = db.collection('items')
return collection.find({}).toArray()
}
const updateQuantity = (id, quantity) => {
const collection = db.collection('items')
return collection.updateOne({ _id: ObjectId(id) }, { $inc: { quantity } })
}
module.exports = { init, insertItem, getItems, updateQuantity }