Hate Names
Hate Names

Reputation: 1606

Inserting a variable as a key in MongoDB

I am retrieving JSON data from an API and this is a short example of it:

{"hatenames":
    {"id":6239,
     "name":"hatenames",
     "stat1":659,
     "stat2":30,
     "stat3":1414693
    }
}

I am trying to insert it in the MongoDB (using MongoClient) but it won't let me put just the object directly or use a variable as a field name. If I put the var username it will just output it as username in the database field. This is what I would like to work:

collection.insert({object}
collection.insert({username:object[username]}

but it doesn't and I've been stuck on this for the past few hours. The only resolution I found was to set it and then update the field name afterwards, but that just seems lame to have to do every single time, is there no elegant or easy option that I am somehow missing?

Upvotes: 0

Views: 3882

Answers (2)

Gaurav Dave
Gaurav Dave

Reputation: 7504

Try doing this:

MongoClient.connect('mongodb://127.0.0.1:27017/db_name', function(err, db) {
    if(err) throw err;

    someCollection = db.collection('some_collection');
});

someCollection.insert({
    name: hatenames['name']
});

EDIT

For Dynamic approach, I would suggest you to play aroung this function:

Object.keys(hatenames)

this function will return keys in array.

EDIT 2

I have founded a link: Insert json file into mongodb using a variable

See, if that helps.

Upvotes: 1

Salvador Dali
Salvador Dali

Reputation: 222869

First of all, being a programmer, you should forget about "it does not work" phrase. You should describe how it does not work with exact error messages you encounter. Not to your problem.

Just because I can easily do

db.coll.insert({"hatenames":
    {"id":6239,
     "name":"hatenames",
     "stat1":659,
     "stat2":30,
     "stat3":1414693
    }
})

or var a = {"hatenames":{"id":6239, "name":"hatenames", "stat1":659, "stat2":30, "stat3":1414693}}; and db.coll.insert(a),

I think that the problem is that your object is not really an object, but a string. So I suspect that you have a string returned to you back from that API. Something like '{"hatenames":{...}' and this caused a problem when you try to save it or access the properties. So try to convert it to JSON.

Upvotes: 1

Related Questions