1

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?

2 Answers 2

1

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 insert objHash which is a valid object to insert, now you are inserting jsonHash 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?

var objHash = {
      hashtag: "",
      popularity:1
};
objHash.hashtag = req.body.hashtag;
collection(HASHTAG_COLLECTION).insert(objHash);
Sign up to request clarification or add additional context in comments.

1 Comment

Thankyou! This worked. I guess I didn't need any of that JSON handling.
0

jsonHash is still a string. May be you want to save objHash instead without JSON.stringify ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.