Browse Source

自动初始化数据库

master
OhYee 2 years ago
parent
commit
deecc89fe1
Signed by: OhYee
GPG Key ID: 5A9E1F63ED274FBB
  1. 81
      api/pkg/menu/main.go
  2. 20
      mongo/mongo.go

81
api/pkg/menu/main.go

@ -2,16 +2,91 @@ package menu @@ -2,16 +2,91 @@ package menu
import (
"github.com/OhYee/blotter/mongo"
"github.com/OhYee/blotter/output"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
)
const DatabaseName = "pages"
func init() {
if exists, _ := mongo.CollectionExists("blotter", DatabaseName); exists == false {
initMenus()
}
}
func initMenus() {
output.LogOutput.Printf("Initial database %s", DatabaseName)
mongo.Add(
"blotter",
DatabaseName,
nil,
WithIndex{
Index: 0,
Type: Type{
Icon: "home",
Name: "首页",
Link: "/",
},
},
WithIndex{
Index: 1,
Type: Type{
Icon: "archive",
Name: "归档",
Link: "/archives",
},
},
WithIndex{
Index: 2,
Type: Type{
Icon: "tag",
Name: "标签",
Link: "/tags",
},
},
WithIndex{
Index: 3,
Type: Type{
Icon: "comments",
Name: "评论区",
Link: "/comments",
},
},
WithIndex{
Index: 4,
Type: Type{
Icon: "idcard",
Name: "关于",
Link: "/about",
},
},
WithIndex{
Index: 5,
Type: Type{
Icon: "link",
Name: "优秀博客订阅",
Link: "/friends",
},
},
WithIndex{
Index: 6,
Type: Type{
Icon: "github",
Name: "Github: OhYee",
Link: "https://github.com/OhYee",
},
},
)
}
// Get get all menus
func Get() (res []Type, err error) {
res = make([]Type, 0)
_, err = mongo.Find(
"blotter",
"pages",
DatabaseName,
bson.M{},
options.Find().SetSort(bson.M{"index": 1}),
&res,
@ -23,7 +98,7 @@ func Get() (res []Type, err error) { @@ -23,7 +98,7 @@ func Get() (res []Type, err error) {
}
func Set(menus []Type) (err error) {
if _, err = mongo.Remove("blotter", "pages", bson.M{}, nil); err != nil {
if _, err = mongo.Remove("blotter", DatabaseName, bson.M{}, nil); err != nil {
return
}
@ -33,7 +108,7 @@ func Set(menus []Type) (err error) { @@ -33,7 +108,7 @@ func Set(menus []Type) (err error) {
}
_, err = mongo.Add(
"blotter", "pages", nil,
"blotter", DatabaseName, nil,
slice...,
)
return

20
mongo/mongo.go

@ -233,3 +233,23 @@ func StringToObjectIDs(idStrings ...string) (ids []primitive.ObjectID) { @@ -233,3 +233,23 @@ func StringToObjectIDs(idStrings ...string) (ids []primitive.ObjectID) {
}
return ids
}
func CollectionExists(databaseName string, collectionName string) (exist bool, err error) {
conn, err := NewConn(databaseName, collectionName)
if err != nil {
return
}
defer conn.Close()
db := conn.Client.Database(databaseName)
cursor, err := db.ListCollections(context.TODO(), bson.M{"name": collectionName})
defer cursor.Close(context.TODO())
if err != nil {
return
}
exist = cursor.TryNext(context.TODO())
return
}

Loading…
Cancel
Save