【问题标题】:MongoDB on VPS with mongoose not insertingVPS 上的 MongoDB,mongoose 未插入
【发布时间】:2015-05-04 12:38:44
【问题描述】:

我使用 mongoose 创建了一个简单的演示,它可以在 localhost 上完美运行:

mongoose.connect('mongodb://localhost/mindmap', function(err, next) {
    if(err) return next(err);
    console.log('database connected');
});

它通过简单的查找来获取数据:

/* GET mindmaps. */
router.get('/', function(req, res, next) {
  Mindmap.find(function (err, mindmaps) {
    if (err) return next(err);

    res.json(mindmaps);
  });
});

并通过socket连接添加数据

  // handle adding new mindmaps
  socket.on('mindmap.add', function (data) {
    Mindmap.create(data, function (err, mindmap) {
      if (err) throw err;

      mindmaps.push(mindmap);
      io.sockets.emit('mindmap.add', mindmap);
    });
  });

现在所有这些都在本地运行良好。

今天我在我的 CentOS 6.5 VPS 上安装了 npm、bower、应用程序本身和 MongoDB。我启动了 mongo 服务并在服务器上更改了 app.js 以连接到正确的 ip/port:

mongoose.connect('mongodb://127.0.0.1:27017/mindmap', function(err, next) {

当我使用node bin/www 启动应用程序时,connect 不会引发任何错误,只是表明数据库已连接。 /mindmap 给出一个空数组(此时这是合乎逻辑的)。通过套接字连接添加一个新的思维导图甚至会发出一个正确的mindmap 对象,并且 html 会显示它。没有错误,但也没有保存任何内容,并且在刷新时它再次开始为空。同样在 mongo shell 中,集合中没有任何内容..如果我手动添加一些东西,我在 /mindmap 中看不到它。

完整的客户端代码在http://mindmap.solidwebcode.com:3000/mindmap

这是模型供参考:

var mongoose = require('mongoose');

var SubjectSchema = new mongoose.Schema({
  title: String,
  x: Number,
  y: Number,
  w: Number,
  h: Number,
  parent: mongoose.Schema.Types.ObjectId
});

var MindmapSchema = new mongoose.Schema({
    name: String,
    theme: String,
    subjects: [SubjectSchema],
    created_at: { type: Date, default: Date.now },
    updated_at: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Mindmap', MindmapSchema);

我使用以下方式安装了 mongodb:

sudo yum --enablerepo=epel install mongodb mongodb-server
sudo service mongod start

也开始 mongo 按预期工作,虽然有一些警告:

Server has startup warnings: 
2015-05-04T13:42:08.955+0200 [initandlisten] 
2015-05-04T13:42:08.955+0200 [initandlisten] ** WARNING: You are running in OpenVZ which can cause issues on versions of RHEL older than RHEL6.
2015-05-04T13:42:08.955+0200 [initandlisten] 

我以前从未在 VPS 上安装并使用过 mongo。我错过了一些琐碎的事情吗?

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    问题不是 MongoDB 没有工作,而是套接字连接开始到 localhost:3000,这与外部服务器不同。所以虽然远程服务器上没有任何事情发生,但本地服务器正在接受套接字连接并在它自己的数据库中添加新记录。

    解决方案很简单:将套接字连接更改为远程地址。

    【讨论】:

      猜你喜欢
      • 2016-10-08
      • 2017-12-22
      • 2016-01-21
      • 2012-04-21
      • 1970-01-01
      • 2016-09-19
      • 2012-02-07
      • 1970-01-01
      • 2016-04-01
      相关资源
      最近更新 更多