【问题标题】:Mongoose Won't Add DocumentMongoose 不会添加文档
【发布时间】:2013-05-13 10:50:46
【问题描述】:

我正在尝试从 heroku 调度程序将条目添加到 mongo db。但目前我只是在使用“node app/bin/trackStats”进行测试

这是我的模型。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var StatsSchema = new Schema({
  // eMail address
  totalblc: { type: Number, required: false},
  date: { type: Date, default: Date.now },
  difficulty: {type: Number, unique: true},
  up: {type: String, required: false},
  // Name
});


module.exports = mongoose.model('Stats', StatsSchema);

这是添加实体的代码 #!/app/bin/node

var request = require('request');
var Stats = require('../models/stats');


function getStats() {
  request('http://someurl.com/', function (error, response, body) {
    if (!error) {
      console.log("tesT");
      console.log(body) // Print the google web page.
      var obj = JSON.parse(body);

      var coins = obj.coins;
      var difficulty = obj.difficulty;
      var up = obj.status;
      var stat = new Stats();
      stat.totalblc = coins;
      stat.difficulty = difficulty;
      stat.up = up;
      stat.save(function (err) {
        if (err) {
          console.log(err);


        }

        console.log("IN");
      });
     console.log("aa"); 
    }
    else {
      console.log(error);
      console.log("TEST");
    }
  });

}

getStats();

它console.logs正确记录所有数据,但没有任何数据添加到数据库中。

【问题讨论】:

  • 也许你找错地方了。文档将在 stats 集合中,而不是 Stats
  • 我相信我已经找到了错误的根源,那就是数据库地址是在 /app/config/initializers/03_mongoose.js 中定义的,而这并没有被阅读或注意到我的脚本。如果我在我的脚本中手动添加 mongoose.connect 它可以工作,但是由于尝试创建两个连接而弄乱了其他页面。所以我还是卡住了
  • 机车应用程序通常使用lcm 命令启动。这不是绝对必要的,您也可以手动实例化 Locomotive 应用程序,但在执行 config/initializers 中的任何内容之前仍然需要它。

标签: node.js mongodb mongoose locomotivejs


【解决方案1】:

根据您的评论:

我相信我已经找到了错误的根源,那就是数据库地址是在 /app/config/initializers/03_mongoose.js 中定义的,而我的脚本没有读取或注意到这一点。如果我在我的脚本中手动添加 mongoose.connect 它可以工作,但是由于尝试创建两个连接而弄乱了其他页面。所以我还是卡住了

...你有一个我在学习猫鼬时遇到的问题。

在 StackOverflow 上,请参阅:

  1. Defining Mongoose Models in Separate Module
  2. express: keep all DRY creating a mongoose connection module (using the new createConnection method)
  3. mongoose and model connections

【讨论】:

    猜你喜欢
    • 2017-03-17
    • 2015-07-12
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    相关资源
    最近更新 更多