Search code examples
node.jsmongodbmongoose

Simple mongoose example not working


I am trying to run a simple mongoose/node example which I found here on 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();

If I get the code right there should be an output in the terminal at the end of the script, where the message "Users found" and all users from the collection should be printed. But I just get the timeout message. Why that?

I am running my server on an Amazon EC2 micro instance. Node, Mongodb and mongoose are installed and a Mongodb server is running (I can interact with it from the terminal via "mongo"). I have also created the directory /data/db.


Solution

  • I don't know about mongoose but u.save() might be asynchronous because it writes to the DB. Try

    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);
        });
    });
    

    Edit: This works fine

    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);
    });