英文:
MGO/GOLANG: Struct to unmarshall a document with
问题
我有一个类似这样的Mongo模式:
var phoneBookSchema = Schema({
user_id: {
type: Schema.Types.ObjectId,
ref: 'User',
index: {
unique : true
},
required: true
},
entries: {
type: [entry],
default: []
},
matches: {
type: [],
default: []
}
});
entry文档的数组如下所示:
var entry = Schema({
_id : false,
phone: {
type: String,
index: true
},
name: {
type: String
},
notified: {
type: Boolean,
default: false,
required: true
}
});
我应该如何在Golang中格式化PhoneBook结构体,以便可以运行以下查询并将结果解组为PhoneBook的数组?
var results []PhoneBook
err = pb.Find(bson.M{}).All(&results)
英文:
I have a Mongo schema that looks like this:
var phoneBookSchema = Schema({
user_id: {
type: Schema.Types.ObjectId,
ref: 'User',
index: {
unique : true
},
required: true
},
entries: {
type: [entry],
default: []
},
matches: {
type: [],
default: []
}
});
The array of entry documents looks like this:
var entry = Schema({
_id : false,
phone: {
type: String,
index: true
},
name: {
type: String
},
notified: {
type: Boolean,
default: false,
required: true
}
});
How do I format the PhoneBook struct in Golang so that I can run a query like this and unmarshall the results into an array of PhoneBooks?
var results []PhoneBook
err = pb.Find(bson.M{}).All(&results)
答案1
得分: 2
我已经弄清楚了,以下是答案,希望对需要的人有用。
type PhoneBook struct {
User_id bson.ObjectId
Entries []Entry
Matches []User
}
type Entry struct {
Phone string
Name string
Notified bool
}
type User struct {
User_id string
Username string
}
我已经将代码翻译成中文了。
英文:
I figured it out, here is the answer for anyone who might find it useful.
type PhoneBook struct {
User_id bson.ObjectId
Entries []Entry
Matches []User
}
type Entry struct {
Phone string
Name string
Notified bool
}
type User struct {
User_id string
Username string
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论