Search code examples
mongodbgomgogo-gin

How to fetchall records in mongodb mgo.v2?


I Want to fetch all records in database By using NAME but, if I am using ALL it is showing 500 internal error but, if I Kept One(JSON) I am getting only one record. What is the solution to fetch all records by Name?

func (uc UserController) Filter(c *gin.Context) {
    var name = c.Params.ByName("Name")
    var json models.User
    err := c.Bind(&json)
    if err != nil {
        log.Fatal("error")
        return
    }
    json.Name = name
    fi := bson.D{{"Name", name}}
    err = uc.session.DB(DB_NAME).C(DB_COLLECTION).Find(fi).All(json)

    if err == nil {
        c.Writer.Header().Set("Content-Type", "application/json")
        c.JSON(201, &json)
    } else {
        c.JSON(500, gin.H{"result": "An error occured"})
    }

}

Solution

  • You should pass an array (var json []models.User) to the All(&json) function, but you're passing one item (var json models.User).