-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbOps.ts
60 lines (48 loc) · 1.6 KB
/
dbOps.ts
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
import {connectMongo} from './connectMango'
import Duck from './duckModel'
import DuckInt from './duckInferface'
export default async function dbOps(ducks: Array<DuckInt>) {
let db = await connectMongo()
const ops = async () => {
// Get data
const gotDucks = await Duck.find({})
const formattedDucks: Array<DuckInt> = gotDucks;
const toCompare: Array<String> = formattedDucks.map((fd) => (fd.infoLink));
const toGetOld: Array<String> = ducks.map((d) => (d.infoLink));
// Compare with current data
let newDucks: Array<DuckInt> = [];
ducks.map((d: DuckInt) => {
if (!toCompare.includes(d.infoLink)) {
newDucks.push(d)
}
})
// send new data
if (newDucks.length > 0) {
let key: string = "_id"
await Promise.all(
newDucks.map(async (nd: any) => {
delete nd[key]
await Duck.create(nd)
})
)
}
// get removed data
let removedDucks: Array<DuckInt> = [];
formattedDucks.map((fd) => {
if (!toGetOld.includes(fd.infoLink)) {
removedDucks.push(fd)
}
})
// delete removed data
if (removedDucks.length > 0) {
await Promise.all(
removedDucks.map(async (rd) => {
await Duck.findOneAndDelete({_id: rd._id})
})
)
}
}
await ops()
// Close connection
db.connection.close()
}