28 lines
549 B
Go
28 lines
549 B
Go
|
|
package mongo
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"context"
|
|||
|
|
"time"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// 文档创建,返回InsertedID
|
|||
|
|
func DocumentCreate(colName string, obj interface{}) (interface{}, error) {
|
|||
|
|
client, err := New()
|
|||
|
|
if err != nil {
|
|||
|
|
return nil, err
|
|||
|
|
}
|
|||
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(config.Timeout)*time.Second)
|
|||
|
|
defer cancel()
|
|||
|
|
defer client.Disconnect(ctx)
|
|||
|
|
col, err := Collection(client, colName)
|
|||
|
|
if err != nil {
|
|||
|
|
return nil, err
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
ret, err := col.InsertOne(ctx, obj)
|
|||
|
|
if err != nil {
|
|||
|
|
return nil, err
|
|||
|
|
}
|
|||
|
|
return ret.InsertedID, nil
|
|||
|
|
}
|