4

I'm learning Node.js + mongodb using a simple tutorial - the problem is that I can't get it to save().

This is the code I'm running:

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

PostSchema = new Schema({
    title: String,
    body: String,
    date: Date
});

mongoose.connect('mongodb://localhost/posterdb');
mongoose.model('Post', PostSchema);
var Post = mongoose.model('Post');

// create a post and save it
var post = new Post();

post.title = 'My first post';
post.body = 'Post body';
post.date = Date.now();

post.save(function(err) {
    console.log('error check');
    if(err) { throw err; }
    console.log('saved');
    mongoose.disconnect();
});

It doesn't print anything on the console. Any ideas?

4
  • 1
    Does the connection get established? Try the event mongoose.connection.on("open", function() { ... }). Commented Dec 7, 2011 at 8:08
  • Hmm, interesting. It doesn't get established. mongoose.connect('mongodb://localhost/posterdb', function(err){ console.log(err); }); Prints : { stack: [Getter/Setter], arguments: undefined, type: undefined, message: 'failed to connect to [localhost:27017]' } Commented Dec 7, 2011 at 8:14
  • 1
    Are you sure the server is running at that host and port? Commented Dec 7, 2011 at 8:19
  • Indeed, the server wasn't running. Had no data directory by default. Thanks! Commented Dec 7, 2011 at 8:28

2 Answers 2

4

Turns out my mongodb server wasn't running because I didn't have a /data/db directory installed by default upon installing mongo in ubuntu. Created that, started the server, everything worked fine. Solved.

Sign up to request clarification or add additional context in comments.

Comments

3

If anyone found this question for the same reason I did, then maybe this will help:

Found that I couldn't save a new object to my collection. I had made a schema method named validate() which interfered with MongoDB's validate() function, so that's why it wasn't saving to the DB and was giving me zero errors. So don't name a method in your schema entitled validate(). Hopefully my dumbness will save you a lot of time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.