Mongodb 匿名结构返回空字段值

Mongodb 匿名结构返回空字段值,mongodb,go,struct,embedding,mgo,Mongodb,Go,Struct,Embedding,Mgo,我可能还没有完全理解匿名结构的概念。在上面的示例中,当查询集合中的所有用户时,id字段将是一个空字符串“”。但是,如果我直接在Userstruct中定义ID字段,则ID显示良好。这不是匿名结构的用途吗?基本上是扩展struct,这样就不必一次又一次地键入它们了 更多示例: type ( Id struct { // I previously forgot to add the `ID` field in my question, it is present in my

我可能还没有完全理解匿名结构的概念。在上面的示例中,当查询集合中的所有用户时,
id
字段将是一个空字符串
”。但是,如果我直接在
User
struct中定义ID字段,则
ID
显示良好。这不是匿名结构的用途吗?基本上是扩展struct,这样就不必一次又一次地键入它们了

更多示例:

type (

    Id struct {
        // I previously forgot to add the `ID` field in my question, it is present in my code but not on this question as @icza pointed it out to me
        ID bson.ObjectId `json:"id" bson:"_id"`
    }

    User struct {
        // When using anonymous struct, upon returning the collection, each of the document will have an empty `id` field, `id: ""`
        Id
        Email string `json:"email" bson:"email"`
        ...
    }

    // This works
    User2 struct {
        ID bson.ObjectId `json:"id" bson:"_id"`
        Email string `json:"email" bson:"email"`
    }
)

这里的问题是,具有
struct
类型(包括嵌入式结构)的字段在MongoDB中显示为嵌入式文档。如果不希望这样,则在嵌入结构时必须指定
“inline”
bson标志:

type SoftDelete struct {
    CreatedAt time.Time `json:"created_at" bson:"created_at"`
    UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
    DeletedAt time.Time `json:"deleted_at" bson:"deleted_at"`
}

type UserModel struct {
    SoftDelete
}

type BlogPost struct {
    SoftDelete
}
“inline”
标记所做的是在MongoDB中,它“展平”嵌入结构的字段,就好像它们是嵌入器结构的一部分一样

同样地:

User struct {
    Id           `bson:",inline"`
    Email string `json:"email" bson:"email"`
}
编辑:以下部分适用于嵌入
bson.ObjectId
的原始
Id
类型。提问者后来澄清说,这只是一个输入错误(此后对问题进行了编辑),是一个命名的非匿名字段。仍然认为下面的信息是有用的

关于
Id
类型,需要注意一点:您的
Id
类型也嵌入了
bson.ObjectId

type UserModel struct {
    SoftDelete `bson:",inline"`
}

type BlogPost struct {
    SoftDelete `bson:",inline"`
}
Id
不仅有一个
bson.ObjectId
字段,而且还嵌入了它。这很重要,因为这样您的
Id
类型将有一个从
bson.ObjectId
升级的
String()
方法,嵌入
Id
User
也将如此。话虽如此,打印或调试类型为
User
的值将很困难,因为您将始终看到它作为单个
ObjectId
打印

相反,您可以将其作为
Id
中的常规字段,在
User
中嵌入
Id
仍将按预期工作:

Id struct {
    bson.ObjectId `json:"id" bson:"_id"`
}

请参阅相关问题+asnwer:

Ohh抱歉,我忘记在第一个代码块中键入
ID
。它实际上在我的代码中,我只是忘了把它添加到这个问题中。感谢您指出
inline
标记。那是为了我,谢谢你!顺便说一句,您现在已经回答了我的两个
mgo
问题,两个问题都被接受了!:)
Id struct {
    ID bson.ObjectId `json:"id" bson:"_id"`
}