MongoDB Error: Cannot create property '_id'

2019-09-15 02:12发布

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条回答
疯言疯语
2楼-- · 2019-09-15 02:54

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);
查看更多
萌系小妹纸
3楼-- · 2019-09-15 02:55

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

查看更多
登录 后发表回答