PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How to run Find.().One() in the new go-mongo-driver

 November 14, 2022     error-handling, go, mongo-go, mongodb, mongodb-query     No comments   

Issue

Currently we are in the process of migrating the mgo(globalsign) driver to go mongo-driver

And I want some alternative way to do Find.().One()

I tried something like below but it did not help

    login = model.LoginModel{}
    err = mongo.Collection.Find(bson.M{"name": MAXCOUNT}).Decode(&loginCount) 

Returned me back with the below error ,

 error was: cannot transform type []interface {} to a BSON Document: WriteArray can only write a Array while positioned on a Element or Value but is positioned on a TopLevel

not sure whether the new Decode method allows a struct value ?

my struct looks something like below


type LoginModel struct {
Username    string  `json:"username"`
Password    string  `json:"password"`

}

Do i need to have corresponding bson values too ?

Trying to run Find.().One() in go-mongo-driver


Solution

Collection.Find() is designed to query multiple elements. It returns a mongo.Cursor which you can use to iterate over the results or get all using Cursor.All().

If you need a single result, use Collection.FindOne() instead.

For example:

ctx := context.Background() // Use / setup your context
c := ... // acquire mongo.Collection

var login model.LoginModel
err = c.FindOne(ctx, bson.M{"name": MAXCOUNT}).Decode(&login)
// check error


Answered By - icza
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing