0

Using mongoose with NodeJs for document population to simulate joins is very common. I'm trying to understand how to achieve something similar with go and mgo.

type User struct {
    Id bson.ObjectId `json:"_id" bson:"_id"`
    UserName string
}

type MessageBoard {
    Id bson.ObjectId `json:"_id" bson:"_id"`
}

type Tag struct {
    Id bson.ObjectId `json:"_id" bson:"_id"`
    text string
}

type Post struct {
    Id bson.ObjectId `json:"_id" bson:"_id"`
    Text string
    MessageBoard bson.ObjectId
    User bson.ObjectId
    Tags []bson.ObjectId
}

I would like to store only User and Tag ids in Post. A user can have many posts and if the user edits UserName all posts should reflect this.

var posts []Post

err := PostCollection.Find(bson.M{"MessageBoard":mBoardId}).All(&posts)
if err != nil {
    return nil, err
}

This is a simple query to get posts, but how do I efficiently get posts with User and Tags models populated?

There is Sleep (an Mgo extension) which appears to do what I am looking for, but I am interested in understanding the performance implications and design options better and if there is a solution using Mgo alone. https://github.com/mansoor-s/Sleep

TheBigC
  • 605
  • 3
  • 9
  • 17

1 Answers1

0

Please check out the following question on Stack Overflow:

How do I perform the SQL Join equivalent in MongoDB?

However, it's not always necessary to simulate joins for a NoSQL database such as MongoDB. You might want to consider doing an extra query or using cache when you need to get User for all Posts.

P.S. Even if you are using SQL database, JOIN statement should be carefully reviewed and is not recommended on production, because of its potential performance issue.

Community
  • 1
  • 1
Andy Xu
  • 1,107
  • 8
  • 10