I'm using Node.js and Express on Heroku, with the MongoDB addon. My database connection works fine and I can successfully push some data in, but not other.
Here is the database connection:
mongodb.MongoClient.connect(mongoURI, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
// Initialize the app.
var server = app.listen(process.env.PORT || dbport, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
I can successfully push my Twitter API response into the database like this:
db.collection(TWEETS_COLLECTION).insert(data);
('data' is just a JSON variable)
But when I try to push another JSON variable into the database in the same method, I get an error. Code:
var jsonHash = '{"hashtag":"","popularity":1}';
var objHash = JSON.parse(jsonHash);
objHash.hashtag = req.body.hashtag;
JSON.stringify(objHash);
collection(HASHTAG_COLLECTION).insert(jsonHash);
And the error:
TypeError: Cannot create property '_id' on string '{"hashtag":"myhash","popularity":1}' at Collection.insertMany... ...
Any ideas what I'm doing wrong?
I don't know where you are getting the
jsonHash
variable from but I think you are doing unecessary JSON-handling here. You are also inserting the wrong variable, you want to insertobjHash
which is a valid object to insert, now you are insertingjsonHash
which is just a string.JSON.stringify(objHash);
is not doing anything as you are not saving the JSON returned from the function. I think you want something like this?jsonHash
is still a string. May be you want to saveobjHash
instead withoutJSON.stringify
?