问题描述
我在Heroku上使用Node.js和Express,以及MongoDB插件.我的数据库连接工作正常,我可以成功地推送一些数据,但不能成功地推送其他数据.
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.
这是数据库连接:
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);
});
});
我可以像这样成功地将Twitter API响应推入数据库:
I can successfully push my Twitter API response into the database like this:
db.collection(TWEETS_COLLECTION).insert(data);
(数据"只是一个JSON变量)
('data' is just a JSON variable)
但是当我尝试用相同的方法将另一个JSON变量推入数据库时,出现错误.代码:
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);
错误:
有什么想法我在做什么错吗?
Any ideas what I'm doing wrong?
推荐答案
我不知道您从哪里获取jsonHash
变量,但我认为您在此处进行了不必要的JSON处理.您还要插入错误的变量,要插入objHash
这是要插入的有效对象,现在要插入jsonHash
,这只是一个字符串. JSON.stringify(objHash);
没有做任何事情,因为您没有保存从函数返回的JSON.我想你想要这样的东西吗?
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);
这篇关于MongoDB错误:无法在字符串上创建属性"_id"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!