<p>Hi folks,</p>
<p>I've created a basic CRUD application using gin and Mongodb (mgo). I can't figure out how to create a subdocument. </p>
<p>For example, if I had:</p>
<pre><code>type Article struct {
Title string `form:"title" json:"title"`
Body string `form:"body" json:"body"`
Categories []*Category
}
</code></pre>
<p>How would I find an article and then insert a category?</p>
<p>Any help much appreciated! </p>
<hr/>**评论:**<br/><br/>koalefant: <pre><p>Haven't tested it so no guarantees, but I assume something like the following:</p>
<pre><code>type Article struct {
Title string `bson:"title" json:"title"`
Body string `bson:"body" json:"body"`
Categories []*Category `bson:"categories" json:"categories"`
}
cat := &Category{}
change := mgo.Change{
Update: bson.M{"$push": bson.M{"categories": cat}},
}
c := session.DB(database).C(collection)
_, err := c.Find(bson.M{"title": "cats in hats et al"}).Apply(change, nil)
if err := nil {
panic("not enough cats in hats")
}
</code></pre></pre>ewanvalentine: <pre><p>Spot on! Thank you so much! </p></pre>hjkelly87: <pre><p>I'm assuming you have already created the documents themselves, and you're only struggling with adding additional categories. If that's not the case, and you're not sure how to insert a document with subdocuments all at once, let me know.</p>
<p>I prefer to do this as one query rather than separately finding an object and then having to update the whole thing (when really you're just appending to an array).</p>
<pre><code>selector := bson.M{"title": titleYouWant}
changes := bson.M{"$push": bson.M{"categories": Category{"My Category"}}}
changeInfo, err := session.DB(database).C(collection).Update(selector, changes)
if err != nil {
// handle error gracefully
} else {
// oh hai it worked
fmt.Println(changeInfo)
}
</code></pre>
<p>A few thoughts:</p>
<ul>
<li>The lowercase "categories" attribute name came from <a href="https://godoc.org/labix.org/v2/mgo/bson#Marshal" rel="nofollow">the mgo.v2/bson docs</a> which explain that it uses the lowercase version of the struct attribute if no <code>bson:actualFieldName</code> is given via golang's struct tags.</li>
<li>My structs always have an ID field, which makes the more foolproof/predictable to find:</li>
</ul>
<p><code>
type Article struct {
Id bson.ObjectId `bson:"_id"`
...
}
</code></p>
<p>*edit: I suck at reddit formatting</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传