简单的猫鼬示例不起作用

时间:2012-07-05 10:20:45

标签: node.js mongodb mongoose

我正在尝试运行一个简单的mongoose / node示例,我在stackoverflow上找到它:

var mongoose = require('mongoose'),
db = mongoose.connect('mongodb://localhost/db'),
Schema = mongoose.Schema;

var sentinel = setTimeout(function(){
    throw "failed to connect to MongoDB after one minute!";
}, 60*1000); // 60 seconds


mongoose.model('User', new Schema({
    properties: {
        name    : { type: String, index: true }
    }
}));    

var User = db.model('User');

var u = new User();
u.name = 'Foo';
u.save();

User.find().all(function(arr) {
    clearTimeout(sentinel); // cancel the timeout sentinel
    console.log('Users found');
    console.log(arr);
    console.log('length='+arr.length);
});

process.stdin.resume();

如果我得到了正确的代码,那么在脚本末尾的终端中应该有一个输出,其中应该打印“Users found”消息和集合中的所有用户。但我只是得到超时消息。为什么?

我在Amazon EC2微型实例上运行我的服务器。安装Node,Mongodb和mongoose并运行Mongodb服务器(我可以通过“mongo”从终端与它进行交互)。我还创建了目录/ data / db。

2 个答案:

答案 0 :(得分:4)

我不知道mongoose但u.save()可能是异步的,因为它写入了DB。试试

u.save(function (err){
    if(err) console.log(err);
    User.find().all(function(arr) {
        clearTimeout(sentinel); // cancel the timeout sentinel
        console.log('Users found');
        console.log(arr);
        console.log('length='+arr.length);
    });
});

编辑:这很好用

var mongoose = require('mongoose');
var connection = mongoose.connect('mongodb://localhost/my_database');

var Schema = mongoose.Schema
var User = new Schema({
    author    : String
  , type      : String
});

var MyUserModel = mongoose.model('User', User); //create and access the model User

var u = new MyUserModel();
u.author = 'authorname';
u.save(function(err){
    if (err) console.log(err);
});

MyUserModel.find({}, function (err,docs) {
    console.log(docs);
});

答案 1 :(得分:0)

我通过在每个使用DB的路由器中添加一个额外的步骤来解决这个问题。

它有点乱,但它有效,100%没有泄漏。

这样的事情:

// file: 'routes/api/v0/users.js'
router
var User = require('../../../models/user').User,
    rest = require('../../../controllers/api/v0/rest')(User),
    checkDB = require('../../../middleware/checkDB');

module.exports = function (app) {
  app.get('/api/v0/users', checkDB, rest.get);
  app.get('/api/v0/users/:id', checkDB, rest.getById);
  app.post('/api/v0/users', checkDB, rest.post);
  app.delete('/api/v0/users', checkDB, rest.deleteById);
  app.put('/api/v0/users', checkDB, rest.putById);
};

// file: 'middleware/checkDB.js'
var HttpError = require('../error').HttpError,
    mongoose = require('../lib/mongoose');

// method which checks is DB ready for work or not
module.exports = function(req, res, next) {
  if (mongoose.connection.readyState !== 1) {
    return next(new HttpError(500, "DataBase disconnected"));
  }
  next();
};

PS如果你更了解解决方案,请告诉我。