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?
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?
mongoose.connection.on("open", function() { ... })
.
– pimvdb
Commented
Dec 7, 2011 at 8:08
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.
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.