Quick mgo question.

polaris · · 668 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi folks,</p> <p>I&#39;ve created a basic CRUD application using gin and Mongodb (mgo). I can&#39;t figure out how to create a subdocument. </p> <p>For example, if I had:</p> <pre><code>type Article struct { Title string `form:&#34;title&#34; json:&#34;title&#34;` Body string `form:&#34;body&#34; json:&#34;body&#34;` 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&#39;t tested it so no guarantees, but I assume something like the following:</p> <pre><code>type Article struct { Title string `bson:&#34;title&#34; json:&#34;title&#34;` Body string `bson:&#34;body&#34; json:&#34;body&#34;` Categories []*Category `bson:&#34;categories&#34; json:&#34;categories&#34;` } cat := &amp;Category{} change := mgo.Change{ Update: bson.M{&#34;$push&#34;: bson.M{&#34;categories&#34;: cat}}, } c := session.DB(database).C(collection) _, err := c.Find(bson.M{&#34;title&#34;: &#34;cats in hats et al&#34;}).Apply(change, nil) if err := nil { panic(&#34;not enough cats in hats&#34;) } </code></pre></pre>ewanvalentine: <pre><p>Spot on! Thank you so much! </p></pre>hjkelly87: <pre><p>I&#39;m assuming you have already created the documents themselves, and you&#39;re only struggling with adding additional categories. If that&#39;s not the case, and you&#39;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&#39;re just appending to an array).</p> <pre><code>selector := bson.M{&#34;title&#34;: titleYouWant} changes := bson.M{&#34;$push&#34;: bson.M{&#34;categories&#34;: Category{&#34;My Category&#34;}}} 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 &#34;categories&#34; 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&#39;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:&#34;_id&#34;` ... } </code></p> <p>*edit: I suck at reddit formatting</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

668 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传