I have a Firebase database that looks like this:
{
"users" : [ null, {
"name" : "John",
"recipes" : {
"34" : {
"name" : "Chicken Parmesan"
}
}
} ]
}
I'm trying to access the data through a Golang API. When I'm running the API locally, it works. However, when I try to use the API on AppEngine, Firebase returns null.
This is how I'm calling it:
userID := req.URL.Query().Get("user_id")
// Make call to API or to Database here, and then write out results
var user interface{}
f.Auth(<FIREBASE_SECRET>)
if err := f.Child("users/" + userID).Value(&user); err != nil {
fmt.Print(w, err)
}
json.NewEncoder(w).Encode(user)
Any ideas on why this may not be working?
Related
I am trying to format my response from a server in an array of multiple object JSON. I tried slice and []Struct but I believe I am not able to understand their usage correctly.
I tried the method mentioned here - https://play.golang.org/p/9OEPzbf0Me0 but didn't work in my case
I am using golang to get response for a query parameter
router.HandleFunc("/v1.0/singles", GetInfo).Methods("GET").Queries("Group", "{group}")
//controller.go
func SendToServer(jsonValue []byte, command string) (models.JSON, error) {
var pdatar models.JSON
s := []string{"http://172.xx.xxx.xx:xxxxx/", command}
response, err := http.Post(strings.Join(s, ""), "application/json", bytes.NewBuffer(jsonValue))
data, err := ioutil.ReadAll(response.Body)
err = json.Unmarshal(data, &pdatar)
mdatar := make(models.JSON)
mdatar["ID"] = pdatar["id"]
mdatar["Name"] = pdatar["name"]
fmt.Println(mdatar) //This is how it is coming map[ID:[877,235], Name:[FCU, GHP]]
/*Another attempt
var temp models.Arr
json.Unmarshal(data, &temp)
fmt.Println(temp) ---- returning null
*/
return mdatar, nil
}
func (c Controller) GetSingle(pdata models.Single) (models.JSON, error) {
mdata := make(models.JSON)
mdata["group"] = pdata.Group
jsonValue, err := json.Marshal(mdata)
pdatar, err := SendToServer(jsonValue, "func_info")
return pdatar, nil
// json.NewEncoder(w).Encode(pdatar) //sending this to my main function
}
//model.go
type JSON map[string]interface{}
type Single struct {
ID int `json:"id"`
Name string `json:"name"`
}
type Data []Single
type Arr [][]string
I have a response from my API in a format
{
"id":[877,235,312,429],
"name" ["FCU","GHP","c","d"],
"group":["x","x","y","z"]
}
With Current Code I am receiving a response
{"id":[877 235], "name": ["FCU" "GHP"]
Though I am expecting a response
{
"data":
[
{"id": 877
"name" : "FCU"
}
{"id": 235
"name": "GHP"
}
]
}
Your mdatarr doesn't change the format any, so this result makes sense.
If the data received from the server is in the format:
{
"id": [877,235,312,429],
"name" ["FCU","GHP","c","d"],
"group": ["x","x","y","z"]
}
then you will need translate it. Ideally you'd fix the server so that it sends data in the format:
{
{
"id": 877,
"name": "FCU",
"group": "x",
},
...
}
If the server could send something like the above, then you could simply unmarshal it into a models.Data object.
If that is not an option, and you really need to do the translation client-side, then you'll need a for loop that does something like this:
ids := pdatarr["id"]
names := pdatarr["name"]
...
if len(ids) != len(names) {
return nil, errors.New("Invalid input format")
}
var mdatar models.Data
for i := range(ids) {
mdatar = append(mdatar, models.Single{ids[i], names[i], ...})
}
return models.JSON{"data": mdatar}, nil
I have inserted data into mongodb in the following way
{
"_id" : ObjectId("5c80e9cc3bf127cfc80ba5dc"),
"resp" : [
{
"name" : "by",
"gender" : "synced",
"age" : "response",
"hobby" : "submitted",
"mobile" : "revision"
},
{
"name" : "byoooooo",
"gender" : "sytewed",
"age" : "se",
"hobby" : "subed",
"mobile" : "revissaaon"
}
]
}
Using this method
func (d *CollectDAO) Insert(responses []*models.FormData) error {
resp := models.Responses{
Data: responses,
}
err := db.C(formsCollection).Insert(resp)
return err
}
This is the struct used in the insert method
type FormData struct {
Name string `csv:"name" json:"name" bson:"name"`
Gender string `csv:"gender" json:"gender" bson:"gender"`
Age string `csv:"age" json:"age" bson:"age"`
Hobby string `csv:"hobby" json:"hobby" bson:"hobby"`
MobileNo string `csv:"mobile" json:"mobile" bson:"mobile"`
}
The handler reads sample csv data from a file. This is the csv data
name,gender,age,hobby,mobile
by,synced,response,submitted,revision
byoooooo,sytewed,se,subed,revissaaon
And then inserts that into mongo
When querying all the documents of my collection I get an empty response
func (d *CollectDAO) FindAll() (models.Responses, error) {
var responses []models.Responses
err := db.C(formsCollection).Find(nil).All(&responses)
if err != nil {
log.Fatal(err)
}
log.Printf("all docs %v\n", responses)
return responses, err
}
When I try to log the value of the struct I get an empty struct. This is the responses struct that I am using at the end to put the slice of response in.
type Responses struct {
Data []*FormData `json:"response"`
}
What am I doing wrong? I just need to implement a handler that will return all the data in a collection as a struct.
On the client side I get this error
unexpected end of JSON input
{ObjectIdHex("") []}
The mgo package uses the bson tag to map struct fields to document fields in MongoDB.
So your Responses type should look something like this:
type Responses struct {
Data []*FormData `json:"response" bson:"resp"`
}
Note that you have to save documents with this struct (with bson tag) to be able to fetch results into values of this type.
I'm trying to get a specific array of objects depending on ObjectId they have.
Here is my MongoDB database:
{
"_id" : ObjectId("59edb571593904117884b721"),
"userids" : [
ObjectId("59edb459593904117884b71f")
],
"macaddress" : "MACADDRESS",
"devices" : [ ],
"projectorbrand" : "",
}
{
"_id" : ObjectId("59edb584593904117884b722"),
"userids" : [
ObjectId("59edb459593904117884b71f"),
ObjectId("59e4809159390431d44a9438")
],
"macaddress" : "MACADDRESS2",
"devices" : [ ],
"projectorbrand" : "",
}
The command in MongoDB is:
db.getCollection('co4b').find( {
userids: { $all: [ ObjectId("59edb459593904117884b71f") ] }
} )
This will work and will return an array filtered correctly.
I would like to translate this query in Golang.
Here is my code:
pipe := bson.M{"userids": bson.M{"$all": objectId}}
var objects[]models.Objects
if err := uc.session.DB("API").C("objects").Pipe(pipe).All(&objects); err != nil {
SendError(w, "error", 500, err.Error())
} else {
for i := 0; i < len(objects); i++ {
objects[i].Actions = nil
}
uj, _ := json.MarshalIndent(objects, "", " ")
SendSuccessJson(w, uj)
}
I'm getting error like wrong type for field (pipeline) 3 != 4. I saw that $all needs string array but how to filter by ObjectId instead of string?
Thanks for help
You are attempting to use the aggregation framework in your mgo solution, yet the query you try to implement does not use one (and does not need one).
The query:
db.getCollection('co4b').find({
userids: {$all: [ObjectId("59edb459593904117884b71f")] }
})
Can simply be transformed to mgo like this:
c := uc.session.DB("API").C("objects")
var objects []models.Objects
err := c.Find(bson.M{"userids": bson.M{
"$all": []interface{}{bson.ObjectIdHex("59edb459593904117884b71f")},
}}).All(&objects)
Also note that if you're using $all with a single element, you can also implement that query using $elemMatch, which in MongoDB console would like this:
db.getCollection('co4b').find({
userids: {$elemMatch: {$eq: ObjectId("59edb459593904117884b71f")}}
})
Which looks like this in mgo:
err := c.Find(bson.M{"userids": bson.M{
"$elemMatch": bson.M{"$eq": bson.ObjectIdHex("59edb459593904117884b71f")},
}}).All(&objects)
I am able to connect to mongodb through my nodejs api but for some reason data is not returned. When i query mongodb from console , here is what i get :
MongoDB Enterprise > db.patients.find();
{ "_id" : ObjectId("58c9a5dd1eb8c7c1c68778ca"), "FName" : "n", "LName" : "ri", "Email" : "abc#yahoo.com", "phone" : "1234567890" }
here is the code from nodejs:
app.get('/api/patients',function(req,res){
Patient.getPatients(function(err,patients){
if(err){
throw err;
}
console.log(patients.length);
res.json(patients);
});
});
and this is getPatients method:
var Patient = module.exports = mongoose.model('patient',patientSchema);
// get patients
module.exports.getPatients = function(callback,limit){
Patient.find(callback);
}
But the browser always shows "[]" and no data. When i look at length of array ( console.log(patients.length)) in API , i get 0. Not sure why data is not returned.
Can someone pls point me what may be the issue ?
Update
Based on suggestions, I did following changes. I created 2 collections just to make sure that the collection exists. So i have patient and patients collections.
MongoDB Enterprise > db.patient.find();
{ "_id" : ObjectId("58cfe4551eb8c7c1c68778cc"), "FName" : "V", "LName" : "K", "Email" : "abc#yahoo.com", "phone" : "1234567890" }
{ "_id" : ObjectId("58cfe4601eb8c7c1c68778cd"), "FName" : "V1", "LName" : "K1", "Email" : "abc#yahoo.com", "phone" : "1234567890" }
MongoDB Enterprise > db.patients.find();
{ "_id" : ObjectId("58cfe42d1eb8c7c1c68778cb"), "FName" : "V", "LName" : "K", "Email" : "abc#yahoo.com", "phone" : "1234567890" }
Here is the code from nodejs file:
var mongoose = require('mongoose');
var patientSchema = mongoose.Schema({
FName: {
type : String
},
LName: {
type : String
},
Email: {
type : String
},
phone: {
type : String
},
},
{collection : 'patient'});
var Patient = module.exports = mongoose.model('patient',patientSchema);
// get patients
module.exports.getPatients = function(callback,limit){
console.log('test2');
Patient.find({}, function(err, patients) {
if (err) throw err;
// object of all the users
console.log(patients.length);
});
}
when i run this code, it prints 'test2' and '0' for me but not actual results. Can someone help with this ?
Are you sure you defined your schemas well and its exported very well... If yes then do something like this from your nodejs scripts
//get the model
var Patient = mongoose.model('patient',patientSchema);
// get all the patients
Patient.find({}, function(err, patients) {
if (err) throw err;
// object of all the users
console.log(patients);
});
I believe this should work
The answer above, while executing the find on the Patient model correctly, will not get the results back to your api response. I think if you change your getPatients code to this:
var Patient = module.exports = mongoose.model('patient',patientSchema);
module.exports.getPatients = function(callback) {
Patient.find({},
function(err, data) {
callback(err,data);
}
);
}
It will work. If that doesn't work, I'd want to see the entire code file to make sure the app.get can access the getPatients function - but you would get an error if that wasn't the case. So, I think this will work.
I figured my code was correct but connection string was incorrect.
Incorrect Connection string :
mongoose.connect('mongodb://localhost:27017/');
Correct connection string:
mongoose.connect('mongodb://localhost:27017/patients');
I am currently trying to save an objectId in another user's array. unfortunately, I am getting an error. here is what I tried :
let name = (PFUser.currentUser()!["FirstName"] as! String) + " " + (PFUser.currentUser()!["LastName"] as! String)
let News = News(title: "\(name) accepted your ...", user: PFUser.currentUser()!)
News.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if (success){
let user = self.interest.user as! User
user.joinNews(News.objectId!)
} else {
print("--------")
}
})
And here is the func joinNews I created for this :
public func joinNews(newsId: String) {
newsIds.insert(newsId, atIndex: 0)
saveInBackgroundWithBlock { (success, error) -> Void in
if error != nil {
print("\(error!.localizedDescription)")
}
}
}
Thanks in advance for you help !
The User object has a special security : it can only be updated by the user itself, that's why you get the error "User cannot be saved unless they have been authenticated via logIn or signUp"
If you want an action of the current user to modify another user object, you need to use a cloud code function, and use the Parse master key, to override this security.
This would look like :
Parse.Cloud.define("addNewsToUser", function(request, response) {
Parse.Cloud.useMasterKey();
var user = new Parse.User();
user.id = request.params.userId;
user.fetch().then(function(object) {
// modify the user here
return user.save();
}).then(function() {
response.success(user);
}, function(error) {
response.error(error.message);
});
});