-
Notifications
You must be signed in to change notification settings - Fork 1
/
db-init.js
54 lines (51 loc) · 1.85 KB
/
db-init.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
54
const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const UserGroup = require('./api/models/userGroup.js');
const User = require('./api/models/user.js');
const init = async function initDatabase () {
try {
// Check if database is already populated
const users = await User.find({ admin: "true" })
if (users.length > 0) throw new Error("Database is already populated")
// UserGroupData
const userGroupData = {
name: 'Administración General',
users: [],
groups: [],
images: [],
devices: [],
displays: [],
description: 'Grupo de administradores',
}
// UserGroupData
const userData = {
admin: 'true',
name: 'admin',
login: 'admin',
email: '[email protected]',
}
// Create userGroup instance
const userGroup = new UserGroup(userGroupData)
// Save userGroup
const { _id: usergroupId } = await userGroup.save()
// Update userGroup with the corresponding url
const usergroupUrl = `${process.env.API_URL}usergroups/${usergroupId}`
await UserGroup.findByIdAndUpdate({ _id: usergroupId }, { $set: { url: usergroupUrl } })
// Add user password and userGroup
userData.password = bcrypt.hashSync('1234', 10);
userData.userGroup = usergroupId
// Create user instance
const user = new User(userData)
// Save user
const { _id: userId } = await user.save()
// Update user with the corresponding url
const userUrl = `${process.env.API_URL}users/${userId}`
await User.findByIdAndUpdate({ _id: userId }, { $set: { url: userUrl } })
// Add user to the userGroup and viceversa
await User.findByIdAndUpdate({ _id: userId }, { $set: { usergroup: usergroupId } })
await UserGroup.findByIdAndUpdate({ _id: usergroupId }, { $addToSet: { users: userId } })
} catch (e) {
console.log(e)
}
}
module.exports = init