mongo-example/mongo/document.go

28 lines
549 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}